我想让一个子类修改一个从其父类继承的类变量。
我想做一些类似的事情:
class Parent(object):
foobar = ["hello"]
class Child(Parent):
# This does not work
foobar = foobar.extend(["world"])
理想情况下:
Child.foobar = ["hello", "world"]
我能做到:
class Child(Parent):
def __init__(self):
type(self).foobar.extend(["world"])
但是每次我实例化 Child 的实例时,“world”都会附加到列表中,这是不希望的。我可以将其进一步修改为:
class Child(Parent):
def __init__(self):
if type(self).foobar.count("world") < 1:
type(self).foobar.extend(["world"])
但这仍然是一个 hack,因为我必须先实例化 Child 的一个实例才能工作。
有没有更好的办法?
最佳答案
假设您想在子类中有一个单独的列表,而不是修改父类的列表(这似乎没有意义,因为您可以直接修改它,或者将预期值放在那里):
class Child(Parent):
foobar = Parent.foobar + ['world']
请注意,这与继承无关,这可能是件好事。
关于python - python中的继承类变量修改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13404476/