作为一个在Java中工作过的人,我在Python中对类属性的多态引用有一点难以理解。
我想做的是在基类中有一个方法,它修改了基类的"静态"变量(又名类属性),但是当从派生类调用该方法时,该方法修改了派生类的类属性,而不是基类。注意,我没有重写派生类中的方法。
例如,我有这样的内容:
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))
我想:"foo"
我得到:"foo, bar"
现在,我明白了,因为"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']