我不明白为什么结果是“ B的__new __()调用A的__init __()调用A的__new __()调用”

问题描述 投票:0回答:1
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称为...

python oop
1个回答
0
投票

对于类Foo,仅当Foo.__init__返回Foo()的实例时,Foo.__new__才由Foo自动调用。 B.__new__返回None,因此不会调用B.__init__

© www.soinside.com 2019 - 2024. All rights reserved.