Reputation: 110143
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
Upvotes: 1
Views: 35
Reputation: 7210
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
...
Upvotes: 2