Reputation: 77
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, i.e. 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()"
Upvotes: 0
Views: 2268
Reputation: 41
The __new__
method must return an instance of the class. Otherwise, init will not be called. The code should work like this.
class Spam:
def __new__(cls):
#self.__init__(self)
print("1", end = " ")
return super().__new__(cls)
def __init__(self):
print("2", end = " ")
class Eggs(Spam):
def __new__(cls):
print("3", end = " ")
return super().__new__(cls)
def __init__(self):
print("4", end = " ")
e = Eggs()
s = Spam()
Another issue is that the __new__
method acts like a static method. So it does not contain self
.
Upvotes: 0
Reputation: 65
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.
Upvotes: 1