【发布时间】:2012-11-04 11:07:15
【问题描述】:
我想让一个子类修改一个从其父类继承的类变量。
我想做一些类似的事情:
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 的实例才能工作。
有没有更好的办法?
【问题讨论】:
标签: python python-2.7