Python Metaclass

  1. Metaclass is class which creates other class (its instance is other class)
  2. 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
  3. 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
  4. If that is not found, it checks for a global variable named __metaclass__ and uses it if it exists.
  5. Otherwise,the class is a classic class, and types.ClassType is used as the metaclass
  6. metaclass (always) passes three arguments (to its constructor): the class name, the tuple of base classes to inherit from, and the (class) attribute dictionary
  7. "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)
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'
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值