Python - how to get class instance reference from an attribute class? -
class a() att = b() class b() ... = a() b = b() a.att = b
how can b reference of ? need attribute of here.
thanks!
you can make generic "reference()" class, keep reference of in attributes dictionnary.
class reference(object): def __init__(self): self.references = {} def __setattr__(self, key, value): if hasattr(self, 'references'): if isinstance(value, reference): if not key in value.references: value.references[key] = [] value.references[key].append(self) elif value none , hasattr(self, key): old = getattr(self, key).references if key in old , self in old[key]: old[key].remove(self) super(reference, self).__setattr__(key, value)
and then, create classes :
class a(reference): def __init__(self): super(a, self).__init__() self.att = none class b(reference): def __init__(self): super(b, self).__init__() self.att = none
and use :
a = a() b = b() print 'a references', a.references print 'b references', b.references # references {} # b references {} a.att = b print 'a references', a.references print 'b references', b.references # references {} # b references {'att': [<__main__.a object @ 0x7f731c8fc910>]}
at end, you'll have reference reference class properties
Comments
Post a Comment