有两个类 A、B 均为单例,B 继承 A。实例化 B 时发现会先执行 B 的__new__函数,然后再执行 A 的__new__函数,请问各位大佬这是为什么?
class A(object):
_instance = None
def __new__(cls, *args, **kw):
if not cls._instance:
print 'create A instance'
cls._instance = super(A, cls).__new__(cls, *args, **kw)
else:
print 'instance A exists'
return cls._instance
def __init__(self):
print 'A'
class B(A):
_instance = None
def __new__(cls,*args,**kw):
if not cls._instance:
print 'create B instance'
cls._instance = super(B, cls).__new__(cls, *args, **kw)
else:
print 'instance B exists'
return cls._instance
def __init__(self):
print 'B'
b1=B()
输出为:
create B instance
create A instance
B
class A(object):
_instance = None
def __new__(cls, *args, **kw):
if not cls._instance:
print 'create A instance'
cls._instance = super(A, cls).__new__(cls, *args, **kw)
else:
print 'instance A exists'
return cls._instance
def __init__(self):
print 'A'
class B(A):
_instance = None
def __new__(cls,*args,**kw):
if not cls._instance:
print 'create B instance'
cls._instance = super(B, cls).__new__(cls, *args, **kw)
else:
print 'instance B exists'
return cls._instance
def __init__(self):
print 'B'
b1=B()
输出为:
create B instance
create A instance
B
