Saturday, April 20, 2013

__metaclass__ in python

# __metaclass__ in python
print """to understand __metaclass__, you must know the following true:
Everything is an object.
'class' and 'type' are synonyms.
there is a special class named "type"
a class is an object and it's an instance of its metaclass type
a class's __metaclass__ can be set to metaclass type, which is subtype of type
`print type(int)` will print `type 'type'`
"""
class LonelyBear(object):
    class MetaBear(type): #a subclass of type
        def __new__(meta, name, bases, attrs):
            # do stuff...
            return type.__new__(meta, name, bases, attrs)
    __metaclass__ = MetaBear
print    type(LonelyBear)

No comments:

Post a Comment