如何使用基类的函数更改相应的类级别属性而不重载函数?
class A:
a = 0
def addOne(self):
print(A.a) # prints 0
A.a = A.a + 1
print(A.a) # it stores the value of a over all the child classes
class B(A):
a = 0
print(A.a) # prints 0
print(B.a) # prints 0
self.addOne()
print(A.a) # prints 1
print(B.a) # prints 0
Class C(A):
a = 0
print(A.a) # prints 1
print(C.a) # prints 0
self.addOne()
print(A.a) # prints 2
print(C.a) # prints 0
我想在self.addOne()
之后B.a = 1
和C.a = 1
.
我不想使用实例属性,因为我将不得不为所有子类重载 addOne 函数。
选项 1:使用type
函数获取self
的类。
def addOne(self):
cls = type(self)
cls.a += 1
选项 2:将addOne
变成classmethod
:
@classmethod
def addOne(cls):
cls.a += 1