python - python中的继承类变量修改

标签 python python-2.7

我想让一个子类修改一个从其父类继承的类变量。

我想做一些类似的事情:

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/

相关文章:

python - 在 celery worker 中运行测试

python - 为什么带有 Python 扩展的 Visual Studio Code 无法正确导入 "fractions"库?

Python:如何在单独的行上编写字符串列表但没有空行

python - 如何使用 django 创建一个 View 来记录数据库中 ModelMultipleChoiceField 表单的数据?

python - For 循环停止在递归函数中迭代

python - pip install numpy 不起作用 : "No matching distribution found"

python - 是否可以忽略 Matplotlib 的第一个默认绘图颜色?

python - 为什么装饰类会破坏描述符协议(protocol),从而阻止 staticmethod 对象按预期运行?

python - 为什么这个多线程 python 程序可以正确打印 0 到 99?

python - 根据另一个Python列表拆分一个字符列表