python __init__ method in inherited class
我想给子类一些额外的属性,而不必显式调用新方法。那么,有没有一种方法可以给继承类一个不重写父类的
我编写下面的代码纯粹是为了说明我的问题(因此属性命名不好等)。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | 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 |
谢谢你
据我所知,这是不可能的,但是您可以调用超类的init方法,如下所示:
1 2 3 4 | class inheritedclass(initialclass): def __init__(self): initialclass.__init__(self) self.attr3 = 'three' |
号
只需使用
1 2 3 4 | class inheritedclass(initialclass): def __new__(self): self.attr3 = 'three' super(initialclass, self).__init__() |
我强烈建议遵循python的命名约定,以大写字母开始一个类,例如
首先,你要混合
您的代码应该如下所示:
1 2 3 4 5 6 7 8 9 | class initialclass(object): def __init__(self): self.attr1 = 'one' self.attr2 = 'two' class inheritedclass(initialclass): def __init__(self): self.attr3 = 'three' super(inheritedclass, self).__init__() |
这非常简单。定义一个新的
1 2 3 4 5 6 7 8 | # assuming a class Base, its __init__ takes one parameter x class Derived(Base): def __init__(self, x, y): # whatever initialization is needed so we can say Derived is-a Base super(Derived, self).__init__(x) # now, add whatever makes Derived special - do your own initialization self.y = y |
。
在python 3中,您不必(因此出于简单起见,不应该)显式继承
只需从父级的init调用指定的方法,如果它存在:
1 2 3 4 5 6 7 8 9 10 | class initialclass(): def __init__(self): self.attr1 = 'one' self.attr2 = 'two' if hasattr(self, 'init_subclass'): self.init_subclass() class inheritedclass(initialclass): def init_subclass(self): self.attr3 = 'three' |