我想维护A和B对象的计数,B是A的子类。所以计数应该特定于A和B。例如,如果我创建3个A对象和2个B对象,通过构造函数调用,计数对于 A 变为 3+2=5,但我想保留为 3(而不是作为 B 的一部分用作子对象时)。请评论以下代码片段:
class A:
acount = 0 # class variable
def __init__(self, isFullA = True):
if (isFullA):
self.iamFullA = True
A.acount += 1
else:
self.iamFullA = False
def __del__(self):
if (self.iamFullA):
A.acount -= 1
class B(A):
bcount = 0 # class variable
def __init__(self, isFullB = True):
A.__init__(self,False)
if (isFullB):
self.iamFullB = True
B.bcount += 1
else:
self.iamFullB = False
def __del__(self):
if (self.iamFullB):
B.bcount -= 1
#MAIN
L=[]
for i in range(3):
L.append(A())
for i in range(2):
L.append(B())
print "A.acount = " + str(A.acount)
print "B.bcount = " + str(B.bcount)
输出是:
A.acount = 3
B.bcount = 2