我在 Objective-C 中使用过,我有这样的构造:
- (void)init {
if (self = [super init]) {
// init class
}
return self;
}
Python 是否也应该调用父类的实现__init__
?
class NewClass(SomeOtherClass):
def __init__(self):
SomeOtherClass.__init__(self)
# init class
这也是对/错吗__new__()
and __del__()
?
Edit:有一个非常相似的问题:继承和重写__init__在Python中 https://stackoverflow.com/questions/753640/inheritance-and-overriding-init-in-python
如果您需要超级的东西__init__
除了当前班级正在做的事情之外还要做的事情__init__,
您必须自己调用它,因为这不会自动发生。但如果你不需要 super 的任何东西__init__,
无需调用它。例子:
>>> 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__
是同样的方式,(但要小心依赖__del__
对于最终确定 - 考虑通过 with 语句来完成)。
我很少用__new__.
我在中进行了所有初始化__init__.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)