Metaclasses are created just like classes, except they are a subclass of type or another metaclass. Actually, type is itself a metaclass. There isn't any interesting syntax involved with their creation: >>> class MetaClass ( type ): Now, to demonstrate how we can use our overly-primitive metaclass, let's create a class from it. There are two ways to do this. The first way is to create a class from our metaclass just as we would create an object from a normal class. However, we have to make a few changes, or we'll end up with this: >>> A = MetaClass() Traceback (most recent call last): Unless you instruct them to do otherwise, metaclasses accept three arguments: the name of the class to be created, a tuple of the base classes involved and a dictionary containing the class's attributes: >>> A = MetaClass ( 'A', (), {} ) >>> A <class '__main__.A'> We can see our metaclass of our class like this: >>> A.__class__ <class '__main__.MetaClass'> Similarly, we can check the metaclass of an object like so: >>> z = A() >>> z.__class__.__class__ <class '__main__.MetaClass'> Creating some attributes is not very complicated. Let's create a class with a few variables: >>> B = MetaClass ( 'B', (), { 'p': 4, 'q': ( '1', 2, '3' ), 'r': "%" } ) >>> B.p 4 >>> B.q ('1', 2, '3') >>> B.r '%' Of course, this is pretty annoying and pointless for anything complex, which leads us to the second method of creating classes from metaclasses. You can simply assign the metaclass to a new-style class's __metaclass__ variable: >>> class C ( object ): __metaclass__ = MetaClass This is a more practical method of creating classes from metaclasses than the previous method.
blog comments powered by Disqus |
|
|
|
|
|
|
|