我尝试缓存属性以获得如下行为:
ply = Player(id0=1)
ply.name = 'Bob'
# Later on, even in a different file
ply = Player(id0=1)
print(ply.name) # outputs: Bob
所以基本上我想保留不同对象之间的值,只要它们的id0
相等
以下是我的尝试:
class CachedAttr(object):
_cached_attrs = {}
def __init__(self, defaultdict_factory=int):
type(self)._cached_attrs[id(self)] = defaultdict(defaultdict_factory)
def __get__(self, instance, owner):
if instance:
return type(self)._cached_attrs[id(self)][instance.id0]
def __set__(self, instance, value):
type(self)._cached_attrs[id(self)][instance.id0] = value
你可以这样使用这个类:
class Player(game_engine.Player):
name = CachedAttr(str)
health = CachedAttr(int)
好像有用。然而,我的一个朋友(有点)评论道:
You are storing objects by their id (memory address) which is most likely going to leaks or get values of garbage collected objects from a new one which reused the pointer. This is dangerous since the id itself is not a reference but only an integer independent of the object itself (which means you will most likely store freed pointers and grow in size till you hit a MemoryError).
我经历了一些随机的车祸,这可能是车祸的原因吗?
如果是这样,是否有更好的方法来缓存除id
以外的值
编辑:只是为了确保;我的Player
类继承自game_engine.Player
,它不是由我创建的(我只是为其他游戏创建了一个mod),而game_engine.Player
总是通过从玩家的id0
获取玩家的新实例来使用。所以这不是我定义的行为
不是
__init__
,而是看__new__
。在那里,在dict中查找唯一的对象并返回它,而不是粘贴一个新的对象。这样,您就可以避免在需要对象的任何地方对其进行不必要的分配。此外,还可以避免不同对象具有不同ID的问题相关问题 更多 >
编程相关推荐