Now let's add some more substance to the picture, since the purpose of metaclasses is not to just sit there and look pretty. We can start by sticking some variables into our metaclass: >>> class MetaA ( type ): The classes created out of this metaclass will have the same variables: >>> class A ( object ):
However, this isn't a very good use at all for metaclasses, since a regular class could do the same thing if A were to subclass it, and the process would be a bit simpler. However, just as a normal class can initialize an object, a metaclass can initialize a class: >>> class MetaB ( type ): As you can see, the __init__ method accepts four variables: cls, name, bases and dct. The cls variable can be compared to self in normal classes. However, since we are dealing with a class instead of an object, it is named a bit differently. The name variable simply contains the name of the class, the bases variable contains a tuple of base classes, and the dct variable contains a dictionary of attributes. Another common name for this last variable is dict, though that gets in the way of the dictionary type since they share the same name in that situation. The __init__ method is called as soon as our class is created: >>> class B ( object ): The MetaB class simply displays the name of each variable. As you can see above, the dictionary of attributes provides us with an interesting link to the class's internals. This is a significant feature, and it gives us a lot of power over classes. It allows us to make some pretty interesting modifications to things that would not otherwise be possible. Consider class C: >>> class C: Now, suppose that we didn't want to create that chain at the end, which assigns alternate names for the one method. We could use a metaclass to eliminate the need for that. For example, we could define the method as multi_one_two_three_four_five and have a metaclass rip it apart for us, creating methods one through five. It's actually pretty simple: >>> class MetaD ( type ): # If the key starts with multi_, perform our work # Split the name to get the aliases # Define the new names We simply loop through the dictionary, and if the attribute name starts with “multi_”, then we break it apart at each underscore and re-assign the value to each piece of the name. Here's our metaclass in action: >>> class D ( object ):
Metaclass MetaD might not be completely practical, but it demonstrates the power of metaclasses. We can use metaclasses to alter the behavior of classes, allowing for new levels of control over classes.
blog comments powered by Disqus |
|
|
|
|
|
|
|