class A:
def __new__(self):
self.__init__(self)
print("A's __new__() invoked") #print if called
def __init__(self):
print("A's __init__() invoked") #print if called
class B(A):
def __new__(self):
print("B's __new__() invoked") #print if called
def __init__(self):
print("B's __init__() invoked") #print if called
def main():
b = B() #create an object of B
a = A() #create an object of A
main()
为什么结果是“ B的new()被调用A的init()被A的new()所调用?我想知道为什么不调用B的init方法。” >
A类:def __new __(self):self .__ init __(self)print(“ A的__new __()被调用”)#print如果被调用def __init __(self):print(“ A的__init __()被调用”)#print if称为...
对于类Foo
,仅当Foo.__init__
返回Foo()
的实例时,Foo.__new__
才由Foo
自动调用。 B.__new__
返回None
,因此不会调用B.__init__
。