0

Lets suppose this example: Two siblings classes where one loads the other class as a new attribute and then i wish to use this attribute from the main class inside the sibling.

a = 2
class AN(object):
   def __init__(self,a):
       self.aplus = a + 2
       self.BECls = BE(a)


class BE(object):
   def __init__(self,a):
       print a

   def get_aplus(self):
       ????

c = AN(a)

and i'd like to do:

c.BECls.get_aplus() 

and this shall return something like self.self.aplus (metaphorically), that would be 4

Resuming: get aplus attribute from AN inside BE class, without declaring as arguments, but doing a "Reverse introspection", if it possible, considering the 'a' variable must be already loaded trough AN.

Sorry if I not made myself clear but I've tried to simplify what is happening with my real code.

I guess the problem may be the technique i'm using on the classes. But not sure what or how make it better.

Thanks

AndreLobato
  • 170
  • 1
  • 12

1 Answers1

2

OP's question:

get aplus attribute from AN inside BE class, without declaring as arguments, but doing a "Reverse introspection", if it possible, considering the 'a' variable must be already loaded trough AN.

The closest thing we have to "reverse introspection" is a search through gc.getreferrers().

That said, it would be better to simply make the relationship explicit

class AN(object):
   def __init__(self,a):
       self.aplus = a + 2
       self.BECls = BE(self, a)

class BE(object):
   def __init__(self, an_obj, a):
       self.an_obj = an_obj
       print a

   def get_aplus(self):
       return self.an_obj.aplus

if __name__ == '__main__':
    a = 2
    c = AN(a)
    print c.BECls.get_aplus()     # this returns 4
Raymond Hettinger
  • 216,523
  • 63
  • 388
  • 485
  • I think this would be one way to work this out, but on my real case i really like to use any argument alredy passed to the main load class, otherwise i would need to pass several objects to others several loaded classes, and this feels me like doing too much repetitions. This way going backwards seems more logical. I'll try to explore getreferrers and see if work it out. Thanks, answer came surprisingly fast. – AndreLobato Apr 29 '12 at 00:54
  • I tried to use gc functions but none of them give me the object i needed. Cheers for the answer anyway. Hope to find some smart way out to this problem. Still not sussed. This answer is the closest solution so far. – AndreLobato Apr 29 '12 at 02:34