因为元类是用来创建类的类,所以如果一个类定义了__metaclass__,那么在这类定义的时候就会调用它的元类,来创建它。
代码如下:
#coding:utf-8
class FA(type):
def __new__(cls, name, base, attr):
print name
print base
print attr
print "it is in fa's new"
new_obj = super(FA, cls).__new__(cls, name, base, attr)
return new_obj
class FB(object):
def __init__(self):
print "it is in FB's init"
self.group = 'china'
class FC(FB):
__metaclass__ = FA
def __init__(self):
print "it is in FC's init"
self.number = 3
#fc = FC()
print "=" * 20
fa = FA('fa_name', (), {'age':22})
|
运行结果如下:
C:\>python test.py
FC
(
,)
{'__module__': '__main__', '__metaclass__': , '__init__': <
function __init__ at 0x00B712B0>}
it is in fa's new
====================
fa_name
()
{'age': 22}
it is in fa's new
有趣的是如果把fc = FC()这句前面的注释删掉,运行结果也会和上面的一样,这是因为在定义FC的时候在
__metaclass__ = FA这里,就会调用FA的__new__来创建类FC了。
如果将FB和FC类都注释起来,即只有元类,而没有他的子类,则运行结果:
====================
fa_name
()
{'age': 22}
it is in fa's new
阅读(949) | 评论(0) | 转发(0) |