I'm used that in Objective-C I've got this construct:
- (void)init {
if (self = [super init]) {
// init class
}
return self;
}
Should Python also call the parent class's implementation for __init__
?
class NewClass(SomeOtherClass):
def __init__(self):
SomeOtherClass.__init__(self)
# init class
Is this also true/false for __new__()
and __del__()
?
Edit: There's a very similar question: Inheritance and Overriding __init__
in Python
If you need something from super's __init__
to be done in addition to what is being done in the current class's __init__,
you must call it yourself, since that will not happen automatically. But if you don't need anything from super's __init__,
no need to call it. Example:
>>> class C(object):
def __init__(self):
self.b = 1
>>> class D(C):
def __init__(self):
super().__init__() # in Python 2 use super(D, self).__init__()
self.a = 1
>>> class E(C):
def __init__(self):
self.a = 1
>>> d = D()
>>> d.a
1
>>> d.b # This works because of the call to super's init
1
>>> e = E()
>>> e.a
1
>>> e.b # This is going to fail since nothing in E initializes b...
Traceback (most recent call last):
File "<pyshell#70>", line 1, in <module>
e.b # This is going to fail since nothing in E initializes b...
AttributeError: 'E' object has no attribute 'b'
__del__
is the same way, (but be wary of relying on __del__
for finalization - consider doing it via the with statement instead).
I rarely use __new__.
I do all the initialization in __init__.