python - 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
解决方案
使用计算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
...
推荐阅读
- asp.net-core - ASP.NET Core 3.0+ 中 MvcMiddleware 的替代品是什么?
- php-7 - 如何使用 switch 语句优化多个 if-else 语句?
- django - /register/new_reg/ register() 处的 TypeError 得到了意外的关键字参数“名称”
- karate - 空手道:无需修改标题的呼叫功能
- java - Flutter 构建失败:未找到:'dart:html' import 'dart:html' http-0.12.2
- php - CodeIgniter:更改密码后如何自动从所有活动会话中注销用户?
- ruby-on-rails - 将用户从 Devise 迁移到 Keycloak
- git - 远程:推送到 github 时权限被拒绝
- git - 在 Github 中将 Repo 转换为分支(保持提交)
- go - 是否可以在弹性中只读取一次?