我想给子类一些额外的属性,而不必显式调用新方法。那么有没有办法给继承类一个 __init__
类型的方法,它不会覆盖父类的 __init__
方法?
我编写下面的代码纯粹是为了说明我的问题(因此属性命名不当等)。
class initialclass():
def __init__(self):
self.attr1 = 'one'
self.attr2 = 'two'
class inheritedclass(initialclass):
def __new__(self):
self.attr3 = 'three'
def somemethod(self):
print 'the method'
a = inheritedclass()
for each in a.__dict__:
print each
#I would like the output to be:
attr1
attr2
attr3
谢谢
原文由 Anake 发布,翻译遵循 CC BY-SA 4.0 许可协议
据我所知这是不可能的,但是你可以像这样调用超类的 init 方法: