简体   繁体   中英

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? 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 ()"

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. If you run my code above you would get the result 4 2.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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