__init __()是否应该调用父类的__init __()? [英] Should __init__() call the parent class's __init__()?
问题描述
我在Objective-C中使用了这种结构:
I'm used that in Objective-C I've got this construct:
- (void)init {
if (self = [super init]) {
// init class
}
return self;
}
Python还应该为__init__
调用父类的实现吗?
Should Python also call the parent class's implementation for __init__
?
class NewClass(SomeOtherClass):
def __init__(self):
SomeOtherClass.__init__(self)
# init class
对于__new__()
和__del__()
这也是对还是错?
Is this also true/false for __new__()
and __del__()
?
有一个非常相似的问题:继承和在Python中覆盖__init__
There's a very similar question: Inheritance and Overriding __init__
in Python
推荐答案
在Python中,调用超类的__init__
是可选的.如果您调用它,那么使用super
标识符还是显式命名超类也是可选的:
In Python, calling the super-class' __init__
is optional. If you call it, it is then also optional whether to use the super
identifier, or whether to explicitly name the super class:
object.__init__(self)
对于对象,由于super方法为空,因此不必严格要求调用super方法.与__del__
相同.
In case of object, calling the super method is not strictly necessary, since the super method is empty. Same for __del__
.
另一方面,对于__new__
,您确实应该调用super方法,并将其返回值用作新创建的对象-除非您明确希望返回其他内容.
On the other hand, for __new__
, you should indeed call the super method, and use its return as the newly-created object - unless you explicitly want to return something different.
这篇关于__init __()是否应该调用父类的__init __()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!