[翻译]  Inherited class variable modification in Python

[CHINESE]  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"])

and ideally have:

理想情况下:

Child.foobar = ["hello", "world"]

I could do:

我可以:

class Child(Parent):
    def __init__(self):
      type(self).foobar.extend(["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:

但是每当我实例化Child的一个实例时,“world”会被附加到列表中,这是不希望的。我可以进一步修改它:

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

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

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

Is there a better way?

有没有更好的办法?

2 个解决方案

#1


38  

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.

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

#2


18  

You should not use mutable values in your class variables. Set such values on the instance instead, using the __init__() instance initializer:

您不应在类变量中使用可变值。使用__init __()实例初始值设定项在实例上设置此类值:

class Parent(object):
    def __init__(self):
        self.foobar = ['Hello']

class Child(Parent):
    def __init__(self):
        super(Child, self).__init__()
        self.foobar.append('world')

Otherwise what happens in that the foobar list is shared among not only the instances, but with the subclasses as well.

否则会发生什么,因为foobar列表不仅在实例之间共享,而且在子类之间共享。

In any case, you'll have to avoid modifying mutables of parent classes even if you do desire to share state among instances through a mutable class variable; only assignment to a name would create a new variable:

在任何情况下,即使您希望通过可变类变量在实例之间共享状态,您也必须避免修改父类的可变项;只有对名称的赋值才会创建一个新变量:

class Parent(object):
    foobar = ['Hello']

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

where a new foobar variable is created for the Child class. By using assignment, you've created a new list instance and the Parent.foobar mutable is unaffected.

其中为Child类创建了一个新的foobar变量。通过使用赋值,您创建了一个新的列表实例,并且Parent.foobar mutable不受影响。

Do take care with nested mutables in such cases; use the copy module to create deep copies if necessary.

在这种情况下,请注意嵌套的mutable;如有必要,使用复制模块创建深层副本。


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
© 2014-2018 ITdaan.com 粤ICP备14056181号