我想维护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
答案 0 :(得分:0)
您正在努力实现复杂化 - 您需要的是为每个类设置一个独特的count
类属性:
class A(object):
_counter = 0
@classmethod
def _inc(cls):
cls._counter += 1
@classmethod
def _dec(cls):
cls._counter -= 1
@classmethod
def get_count(cls):
return cls._counter
def __init__(self):
self._inc()
def __del__(self):
self._dec()
class B(A):
_counter = 0
def __init__(self, wot):
super(B, self).__init__()
self.wot = wot
L=[]
for i in range(3):
L.append(A())
for i in range(2):
L.append(B(i))
print "A.count = {}".format(A.get_count())
print "B.count = {}".format(B.get_count())
请注意,我使用了classmethods
来确保我们访问了class属性,因为self._counter += 1
中的__init__
会创建一个实例属性。您也可以使用type(self)._counter += 1
(或self.__class__._counter += 1
)获得正确的行为,但这有点丑陋imho。
如果这是其他开发人员将在其上构建的API,您可能需要使用自定义元类来确保每个子类都拥有它自己的_counter
,即:
class CounterType(type):
def __new__(meta, name, bases, attribs):
if "_counter" not in attribs:
attribs["_counter"] = 0
return type.__new__(meta, name, bases, attribs)
class CounterBase(object):
__metaclass__ = CounterType
@classmethod
def _inc(cls):
cls._counter += 1
@classmethod
def _dec(cls):
cls._counter -= 1
@classmethod
def get_count(cls):
return cls._counter
def __init__(self):
self._inc()
def __del__(self):
self._dec()
class A(CounterBase):
pass
class B(A):
def __init__(self, wot):
super(B, self).__init__()
self.wot = wot
L=[]
for i in range(3):
L.append(A())
for i in range(2):
L.append(B(i))
print "A.count = {}".format(A.get_count())
print "B.count = {}".format(B.get_count())