class Foo(object):
def __init__(self, *args, **kwargs):
pass
>>> foo = Foo(a, b=c)
- 它的调用
type.__call__(Foo, a, b=c)
...... (而不是type
你的班级的元类)
- ...调用
Foo.__new__(a, b=c)
哪个创建Foo
...的实例
- ...并调用
foo.__init__(a, b=c)
并返回foo
。
换句话说,b = B(*args)
像type.__call__(B, *args)
where这样的工作type.__call__
可以表示为:
class type(object):
def __call__(cls, *args, **kwargs)
obj = cls.__new__(*args, **kwargs)
obj.__init__(*args, **kwargs)
return obj
函数super
仅在您调用它的地方执行(就像普通函数一样)。
装饰是在类和方法的初始化中执行的,在包装器上替换它们。
完整示例:
def dec(func):
print 'decorate', func.__name__
def wrapper(*args):
print 'call wrapper of', func.__name__
return func(*args)
return wrapper
class A(object):
def __new__(*args):
print 'call A.__new__'
return object.__new__(*args)
def __init__(self, *args):
print 'call A.__init__'
class MyMetaclass(type):
def __call__(mcls, *args):
print 'call MyMetaclass.__call__'
return super(MyMetaclass, mcls).__call__(*args)
class B(A):
__metaclass__ = MyMetaclass
@dec
def __new__(*args):
print 'call B.__new__'
return A.__new__(*args)
@dec
def __init__(self, *args):
print 'call B.__init__'
return super(B, self).__init__(*args)
print 'start creating instance'
b = B()
print 'end creating instance'
结果:
decorate __new__
decorate __init__
start creating instance
call MyMetaclass.__call__
call wrapper of __new__
call B.__new__
call A.__new__
call wrapper of __init__
call B.__init__
call A.__init__
end creating instance