- Metaclass is class which creates other class (its instance is other class)
- When executing a class definition, the interpreter has to know the correct metaclass to use. It will look for a class attribute named __metaclass__ first, and if it is there, it will use the class that is assigned to that attribute as the metaclass
- If that attribute has not been defined, it will go up and search an ancestor classfor __metaclass__. All new-style classes must inherit from object or type if there are no other base classes
- If that is not found, it checks for a global variable named __metaclass__ and uses it if it exists.
- Otherwise,the class is a classic class, and types.ClassType is used as the metaclass
- metaclass (always) passes three arguments (to its constructor): the class name, the tuple of base classes to inherit from, and the (class) attribute dictionary
- "type" is the default built-in metaclass.
Example:
class MetaC(type):
def __init__( cls, name, bases, attrd):
super(MetaC, cls).__init__(name, bases, attrd)
print '*** Created class %r at: %s' %(name, ctime())
print '\t' + str(cls)
print '\t' + str(bases)
print '\t' + str(attrd)
class MetaC(type):
def __init__( cls, name, bases, attrd):
super(MetaC, cls).__init__(name, bases, attrd)
print '*** Created class %r at: %s' %(name, ctime())
print '\t' + str(cls)
print '\t' + str(bases)
print '\t' + str(attrd)
print '\tClass "Foo" declaration next.'
# In order to create a Foo class object, the interpreter needs to know to use "what type (template)" to instantiate it.
class Foo(object):
__metaclass__ = MetaC
def __init__(self):
print '*** Instantiated class %r at: %s' %(self.__class__.__name__, ctime())
print '\tClass "Foo" instantiation next.'
f = Foo()
class Bar(Foo):
def __init__(self):
print 'Bar is instantiated'
print '\tDone'
# In order to create a Foo class object, the interpreter needs to know to use "what type (template)" to instantiate it.
class Foo(object):
__metaclass__ = MetaC
def __init__(self):
print '*** Instantiated class %r at: %s' %(self.__class__.__name__, ctime())
print '\tClass "Foo" instantiation next.'
f = Foo()
class Bar(Foo):
def __init__(self):
print 'Bar is instantiated'
print '\tDone'