introspection - Finding what list a class instance is in, in Python -
this problem thus: have instance of class, want know list part of, i.e. :
class test_class() : def test() : print 'i member of list', parent_list foo = [test_class(), 52, 63] bar = ['spam', 'eggs'] foo[0].test()
i print out member of list foo. there arbitrary number of lists given instance of test_class() belong to.
first of all, don't know use-case it, because ideally while putting objects in list, can track them via dict or if have list of lists can check objects in them, better design wouldn't need such search.
so lets suppose fun want know lists object in. can utilize fact gc
knows objects , refers it, here which_list
function tells lists refer ( doesn't mean contains it)
import gc class a(object): pass class b(a): pass def which_list(self): lists_referring_to_me = [] obj in gc.get_referrers(self): if isinstance(obj, list): lists_referring_to_me.append(obj) return lists_referring_to_me = a() b = b() foo = [a, 52, b] bar = ['spam', b] print which_list(a) print which_list(b)
output:
[[<__main__.a object @ 0x00b7fad0>, 52, <__main__.b object @ 0x00b7faf0>]] [[<__main__.a object @ 0x00b7fad0>, 52, <__main__.b object @ 0x00b7faf0>], ['spam', <__main__.b object @ 0x00b7faf0>]]
Comments
Post a Comment