python 全局对象缓存
关于应用程序架构的小问题:
我有一个 python 脚本,作为守护进程运行。
在里面我有很多对象,所有对象都继承自一个类(让我们将其命名为“实体”)
我还有一个主要对象,将其命名为“topsys”
实体由一对(id,类型(=类,粗略))标识,并且他们以许多邪恶的方式联系在一起。它们也一直在创建和删除,并且需要它们来访问其他实体。
所以,我需要一种存储,基本上是字典的字典(每种类型一个),保存所有实体。
问题是,哪个更好:将此字典作为对象属性附加到“topsys”,还是作为类的属性附加到类实体?我会选择第二个(因此实体不需要知道“topsys”的存在),但我对直接在类中使用属性感觉不好。或者也许还有另一种方法?
Little question concerning app architecture:
I have a python script, running as a daemon.
Inside i have many objects, all inheriting from one class (let's name it 'entity')
I have also one main object, let it be 'topsys'
Entities are identified by pair (id, type (= class, roughly)), and they are connected in many wicked ways. They are also created and deleted all the time, and they are need to access other entities.
So, i need a kind of storage, basically dictionary of dictionaries (one for each type), holding all entities.
And the question is, what is better: attach this dictionary to 'topsys' as a object property or to class entity, as a property of the class? I would opt for the second (so entities does not need to know of existence of 'topsys'), but i am not feeling good about using properties directly in classes. Or maybe there is another way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这里没有足够的细节来确定什么是最好的,但一般来说,我会将实际的对象注册表存储为顶级类中的模块级(全局)变量,并在基类中有一个方法来访问它。
或者,完全隐藏 _entites 并公开一些方法,例如。
get_object_by_id
、register_object
,这样您以后就可以更轻松地更改 _entities 本身的存储。顺便说一句,如果您还没有的话,有一个提示:您可能需要查看 在创建像这样的对象注册表时使用weakrefs。
There's not enough detail here to be certain of what's best, but in general I'd store the actual object registry as a module-level (global) variable in the top class, and have a method in the base class to access it.
Alternatively, hide _entites entirely and expose a few methods, eg.
get_object_by_id
,register_object
, so you can change the storage of _entities itself more easily later on.By the way, a tip in case you're not there already: you'll probably want to look into weakrefs when creating object registries like this.
在类上使用属性没有问题。类也只是对象。
在你的情况下,有了这些可用的信息,我也会选择一个类属性,因为不创建依赖关系是很好的,并且以后有时会少一些担心。
There is no problem with using properties on classes. Classes are just objects, too.
In your case, with this little information available, I would go for a class property, too, because not creating dependencies ist great and will be one worry less sometimes later.