编写Python方法来引用派生类中的Class属性,而不是基类

编写Python方法来引用派生类中的Class属性,而不是基类,class,python-3.x,polymorphism,Class,Python 3.x,Polymorphism,作为一个在Java中工作较多的人,我在Python中对类属性的多态性引用的理解上有点困难 我想做的是在基类中有一个方法,它修改基类的“静态”变量(aka class attribute),但是当从派生类调用该方法时,该方法修改派生类的class属性,而不是基类的class属性。注意,我没有重写派生类中的方法 例如,我有一些类似于: class BaseClass: itemList = [] def addItem(thing): BaseClass.itemL

作为一个在Java中工作较多的人,我在Python中对类属性的多态性引用的理解上有点困难

我想做的是在基类中有一个方法,它修改基类的“静态”变量(aka class attribute),但是当从派生类调用该方法时,该方法修改派生类的class属性,而不是基类的class属性。注意,我没有重写派生类中的方法

例如,我有一些类似于:

class BaseClass:
    itemList = []

    def addItem(thing):
        BaseClass.itemList.append(thing)

class Child1(BaseClass):
    pass

class Child2(BaseClass):
    pass

...

Child1.addItem("foo")

Child2.addItem("bar")

print(str(Child1.itemList))
我想要“福”

我得到:“富,酒吧”

现在,我了解到,由于“BaseClass.itemList.append(thing)”,它将引用基类的class属性

换句话说,有没有一种方法可以避免说“BaseClass.itemList”,但保持它为静态,还是需要在每个子类中重写该方法?

您可以拥有一个“静态”类变量,该类的每个实例都可以更改该变量:

class BaseClass:
    itemList = []    
    def addItem(self, thing):
        self.itemList.append(thing)


class Child1(BaseClass):
    itemList = []       


class Child2(BaseClass):
    itemList = []       

# each class has its own "itemList"
# now we can instantiate each class and use the different itemLists:

c1 = Child1()
c1.addItem("foo")

c2 = Child2()
c2.addItem("bar")

c3 = Child1()
c3.addItem("foo2")

print(str(Child1.itemList)) # prints: ['foo', 'foo2']
print(str(Child2.itemList)) # prints: ['bar']

谢谢alfasin,尝试了你写的东西,它做了我想要的,尽管我没想到会有这样的语法。看起来我必须实例化子对象才能使用该方法,即使它修改了类变量。此外,出于某种原因,我认为itemList的本地实例将在派生类中自动创建,但对它的处理表明它不会。谢谢@VictorLegros在Java和其他强类型语言中,我们创建“静态类”(单例)。在python中,我们使用。