Prerequisites This article assumes that you are familiar with the new-style classes introduced in Python 2.2. If you are not familiar with these new classes, the article “More Object Orientation” is worth taking a look at. Likewise, if you are completely unfamiliar with object orientation in Python, the article “Object Orientation in Python” will familiarize you with the concept. Blueprints of Blueprints We are all familiar with the relationship between classes and objects: an object is created from a class. In this model, and I'm sure you have heard this analogy many times before, the class serves as a blueprint for the object. While this two-component model is fine for the majority of situations where object orientation is used, there is another component that you may or may not have heard of before. Let's put that aside for just a second, though. The creation of objects from classes is a fairly customizable process. Using a class, we can tailor an object to make it unique – to suit a specific purpose. For example, take a look at this class: >>> class Style: def __init__ ( self, foreground, background, font, size ): self.foreground = foreground self.background = background self.font = font self.size = size From the Style class, we can easily create numerous instances, each with its own unique attributes: >>> plain = Style ( 'black', 'white', 'Verdana', 9 ) >>> ugly = Style ( 'purple', 'green', 'Arial', 18 ) >>> inverse = Style ( 'white', 'black', 'Verdana', 9 ) >>> christmas = Style ( 'green', 'red', 'Arial', 1 ) >>> halloween = Style ( 'orange', 'black', 'Arial', 10 ) >>> msOffice = Style ( 'black', 'white', 'Times New Roman', 12 ) >>> starOffice = Style ( 'black', 'white', 'Thorndale', 12 ) Each object is created exactly how we want it. We can also make this process dynamic, generating the objects without directly creating them from within the code: >>> import random >>> colors = [ 'black', 'white', 'green', 'red', 'orange', 'brown', 'yellow' ] >>> fonts = [ 'Verdana', 'Arial', 'Times New Roman', 'Helvetica' ] >>> styles = [] >>> for x in xrange ( 10 ): styles.append ( Style ( random.choice ( colors ), random.choice ( colors ), random.choice ( fonts ), random.randint ( 7, 20 ) ) ) Now let's reintroduce that third component I was talking about earlier. If objects can be created uniquely and dynamically, and if classes are technically objects in Python, then can classes be created the same way? Does Python support blueprints of blueprints? The answer is yes. Python supports classes of classes. These are called metaclasses, and their instances are classes themselves.
blog comments powered by Disqus |
|
|
|
|
|
|
|