37,719
社区成员
发帖
与我相关
我的任务
分享
class baseform(object):
pass
class FromMeta(type):
def __init__(cls, name, base, attr):
print 'FormMeta init'
type.__init__(cls, name, base, attr)
class Form(FromMeta('base', (baseform,), {"name":'jiangnan'})):
def __init__(self):
print 'Form init'
class loginForm(Form):
def __init__(self):
print 'loginForm init'
if __name__ == '__main__':
a = loginForm()
class FromMeta(type):
def __init__(cls, name, base, attr):
print 'FormMeta init'
type.__init__(cls, name, base, attr)
通过继承 type 定义了一个元类, 这没什么好说的, 相信楼主的疑惑也不在这里.
class Form(FromMeta('base', (baseform,), {"name":'jiangnan'})):
def __init__(self):
print 'Form init'
这里 FromMeta('base', (baseform,), {"name":'jiangnan'}) 通过实例化一个元类来创建了一个类. 使用元类来实例化一个类对象, 当然会调用它的 __init__ 函数了, 所以输出第一个 FormMeta init 了.
然后, class Form 语句会创建一个类对象. 它使用哪个元类来创建呢? 根据上面说的, 会查找基类的 __class__ 属性. 使用 print FromMeta('base', (baseform,), {"name":'jiangnan'}).__class__ 可以查看到, 它的 __class__ 就是 FromMeta, 也就是说, Form 也会通过实例化 FromMeta 来创建.
所以, 这里就输出了第二个 FormMeta init 了.
同理, 对于 class loginForm 来说, 它的基类是 Form, 通过 print Form.__class__ 可以看到它的元类也是 FormMeta, 所以, loginForm 也是 FormMeta 实例化出来的, FormMeta 实例化对象的时候调用它的 __init__ 就输出了第三个 FormMeta init 了.
这三个 FormMeta init 的输出是和 a = loginForm() 无关的. 去掉它一样会输出前面的三个 FormMeta init.
不知道我说清楚了没有?