python 全局对象缓存

发布于 2024-09-27 05:29:08 字数 365 浏览 6 评论 0原文

关于应用程序架构的小问题:

我有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

心的位置 2024-10-04 05:29:08

这里没有足够的细节来确定什么是最好的,但一般来说,我会将实际的对象注册表存储为顶级类中的模块级(全局)变量,并在基类中有一个方法来访问它。

_entities = []
class entity(object):
    @staticmethod
    def get_entity_registry(): 
         return _entities

或者,完全隐藏 _entites 并公开一些方法,例如。 get_object_by_idregister_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.

_entities = []
class entity(object):
    @staticmethod
    def get_entity_registry(): 
         return _entities

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.

眼前雾蒙蒙 2024-10-04 05:29:08

在类上使用属性没有问题。类也只是对象。

在你的情况下,有了这些可用的信息,我也会选择一个类属性,因为不创建依赖关系是很好的,并且以后有时会少一些担心。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文