简体   繁体   中英

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

Use a computed property

class ModelManager:

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

Also, note that OBJECTS will be shared across your class instances because it is a dictionary initialized at class scope. The NUM_OBJECT property requires initializing the class. If you want NUM_OBJECTS to be a property of the class, use one of the solutions suggested here for class properties.

If you would rather be able to call len around your class (in addition to NUM_OBJECTS ) - you can overkill with metaclasses:

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
    ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM