Python中继承类变量修改

Python中继承类变量修改

本文介绍了Python中继承类变量修改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想让子类修改从父类继承的类变量.

I'd like to have a child class modify a class variable that it inherits from its parent.

我想做一些类似的事情:

I would like to do something along the lines of:

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"都会被附加到列表中,这是不希望的.我可以进一步修改为:

but then every time I instantiate an instance of Child, "world" gets appended to the list, which is undesired. I could modify it further to:

class Child(Parent):
    def __init__(self):
      if type(self).foobar.count("world") < 1:
          type(self).foobar.extend(["world"])

但这仍然是一个黑客,因为我必须在它工作之前实例化一个 Child 实例.

but this is still a hack because I must instantiate an instance of Child before it works.

有没有更好的方法?

推荐答案

假设你想在子类中有一个单独的列表,而不是修改父类的列表(这看起来毫无意义,因为你可以就地修改它,或者把开始时的预期值):

Assuming you want to have a separate list in the subclass, not modify the parent class's list (which seems pointless since you could just modify it in place, or put the expected values there to begin with):

class Child(Parent):
    foobar = Parent.foobar + ['world']

请注意,这与继承无关,这可能是一件好事.

Note that this works independently of inheritance, which is probably a good thing.

这篇关于Python中继承类变量修改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 19:38