简体   繁体   English

Python:为什么有时不调用 __init__ 方法?

[英]Python: why __init__ method sometimes isn't called?

I have a following code:我有以下代码:

class Spam:
    def __new__(self):
        self.__init__(self)
        print("1", end = " ")
    def __init__(self):
        print("2", end = " ")
        
class Eggs(Spam):
    def __new__(self):
        print("3", end = " ")
    def __init__(self):
        print("4", end = " ")
e = Eggs()
s = Spam()

Can someone explain why the result is 3 2 1, ie 4 is not printed?有人可以解释为什么结果是 3 2 1,即 4 没有打印出来吗? Whereas documentation says that而文档说

"In Python the new () magic method is implicitly called before the init () method. The new () method returns a new object, which is then initialized by init ()" “在Python()魔术方法在init()方法之前隐式调用。新的()方法返回一个新的对象,然后将其由init()初始化”

The code should be as follows in order to work,代码应如下所示才能工作,

class Spam:

    def __init__(self):
        print("2", end = " ")
    
class Eggs(Spam):

    def __init__(self):
        print("4", end = " ")

e = Eggs()
s = Spam()

You don't write the new() method because Python has already did all the work for you to not write it.您不必编写 new() 方法,因为 Python 已经为您完成了所有工作,无需编写它。 If you run my code above you would get the result 4 2.如果你运行我上面的代码,你会得到结果 4 2。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM