0

我想维护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
4

1 回答 1

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确保我们正在访问类属性,因为self._counter += 1__init__创建一个实例属性。您也可以使用type(self)._counter += 1(or self.__class__._counter += 1) 获得正确的行为,但这有点难看恕我直言。

如果这是其他开发人员将基于的 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())
于 2015-12-18T10:43:39.533 回答