Reputation: 391
From the documentation of __init__
no non-None value may be returned by __init__(); doing so will cause a TypeError to be raised at runtime.
and I found this code from a framework's extendable base class.
It runs without a runtime error.
class Parent():
def __init__(self, x):
self.x = x
return self.x + 10
class Child(Parent):
def __init__(self, x):
y = super(Child, self).__init__(x)
print(y)
c = Child(5)
I searched about it and agreed that could be nice to pass data from super().__init__ to the derived class without having to relay it through an instance.
But, Why python allows the __init__ return value?
Is it a widely known pattern?
Upvotes: 0
Views: 525
Reputation: 11070
When a class is instantiated, python looks for a method called __init__
and uses it in setting up the new class. If this method returns anything other than None
here, it will raise an error:
class Parent():
def __init__(self, x):
self.x = x
return self.x + 10
Parent(5)
# TypeError: __init__() should return None, not 'int'
However, in your child class you don't let Python use the __init__
method in Parent
- instead you override it by creating your own __init__
which doesn't return anything.
You then call the Parent
__init__
method (via super
) but here you are just calling it as a 'normal' method, rather than using it as part of the class setup, so it won't raise the error.
Upvotes: 1