首页 > 解决方案 > Storing collection information in a class

问题描述

I have a ModelManager which keeps track of creating and destroying new objects. Here's an example:

class ModelManager:
    MAX_OBJECTS = 10
    OBJECTS = {} # hash to model object
    NUM_OBJECTS = len(OBJECTS) # how to dynamically calculate this?

Every time an object is created it is added to OBJECTS and everytime it is deleted it gets popped from OBJECTS.

How would I properly do the NUM_OBJECTS here? Ideally it should be a classmethod/property to act as a calculation. For doing something like the above, what would be the best way?

I would like to call it as ModelManager.NUM_OBJECTS

标签: pythonpython-3.xcollections

解决方案


使用计算property

class ModelManager:

    @property
    def NUM_OBJECTS(self):
        return len(self.OBJECTS)

另外,请注意,OBJECTS它将在您的类实例之间共享,因为它是在类范围内初始化的字典。该NUM_OBJECT属性需要初始化类。如果您想NUM_OBJECTS成为该类的属性,请使用此处为类属性建议的解决方案之一。

如果您希望能够len在您的班级周围打电话(除了NUM_OBJECTS) - 您可以使用元类过度杀伤:

class ModelManagerMeta(type):

    def __len__(cls):
         return len(cls.OBJECTS)

    def NUM_OBJECTS(cls):
         return len(cls.OBJECTS)


class ModelManager(metaclass=ModelManagerMeta):

    MAX_OBJECTS = 10
    OBJECTS = {} # hash to model object
    ...

推荐阅读