开发者

Python Reflection

suppose we have many objects in me开发者_Python百科mory. Each one has a distinct id. How can I iterate the memory to find a specific object that is compared to some id ? In order to grab it and use it through getattr ?


You should maintain a collection of these objects as they are created in a class attribute, then provide a class method for retrieving them.

Something along the lines of:

class Thing(object):
    all = {}

    def __init__(self, id, also, etc):
        self.id = id
        self.all[id] = self

    @classmethod
    def by_id(cls, id):
        return cls.all[id]


You could ask the garbage collector for all existing objects and iterate through that collection to find what you are looking for, but thats probably the wrong thing to do, unless you have very special reasons to do it.


You can make a 'registry' dict that all new instances are subscribed to, with with a mapping of ID->objects:

registry = {}

class MyClass(object):
    def __init__(self, ...):
        id = ...
        registry[id] = self

MyClass.__all__ = registry

This is equivalent to the other accepted solution (the other one is more 'pythonic' however). I have improved this method two ways before: 1) you can create a custom container class for the registry, that allows you to do lookups by more than just IDs; 2) you can also create a metaclass that automatically adds the code, but this can get ugly if you also need metaclasses for something else.

edit: since other answer was acceptable, added ways to factor out design pattern


First to all of you answering me big thanks, what I had in my mind during weekend was this :

for ech in globals():
        if str(type(globals()[ech])).find('instance') != -1:
            if ( globals()[ech].__dict__.has_key('onoma')):
                print "%s, %s, %s"%( ech, globals()[ech].__dict__, id(globals()[ech]) )

which did the job, though I don't know if this good or bad approach ( "onoma" is the greek word for name ). I read in the docs of Pyton about : _id2obj_dict = weakref.WeakValueDictionary() from weakref. And I gave a shot with that too. Nice approach and similar to Ned and ninjagecko I think. But in this case, how can I be sure that an object is released totally from memory ?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜