gpt4 book ai didi

继承类中的python __init__方法

转载 作者:IT老高 更新时间:2023-10-28 20:49:38 24 4
gpt4 key购买 nike

我想给子类一些额外的属性,而不必显式调用新方法。那么有没有办法给继承的类一个 __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

谢谢

最佳答案

据我所知,这是不可能的,但是您可以调用父类(super class)的 init 方法,如下所示:

class inheritedclass(initialclass):
def __init__(self):
initialclass.__init__(self)
self.attr3 = 'three'

关于继承类中的python __init__方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5636419/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com