-1

my code is following in python.

class A(object):
   b = B()
   def d(self):
      print "Hi"

class B():
   def C(self):
      self.__self__.d()#edit ::: i need to call d() method here. i know __self__ is wrong
      # do knowledge for B being variable inside object A needed ? i.e
      # passing parent object via init is needed as shown in some answer ?
      # i search and found im_self __self__ etc...

temp = A()
temp.b.C()#should print hi ?

How do i do this ? i.e. access parent class object's method inside child's method ?

basically I want to send some signal to the parent class from one sibling object to call some method from another sibling object ( not shown in above code ) . I hope i do not sound too much confusing.

iamgopal
  • 8,806
  • 6
  • 38
  • 52
  • 3
    You may not want to hear this, but you're code is probably too tightly coupled and should most likely be re-organized. In any case, though, you should probably clarify a little bit. It's hard to see your intent without any context for these methods. – Wilduck Jul 20 '10 at 14:26

2 Answers2

2

See this previous answer. It's with a derived class instead, but it might be helpful to look into.

You could have A pass itself to B in the init method or as a separate method. As long as that was called before you had a call to B.c() it would work fine. It's not a perfect solution, but it works.

class B():
    def __init__(self, someA):
        self.parent = someA
    def C(self):
        self.parent.d()

class A(object):
   def __init__(self):
       self.b = B(self)
   def d(self):
      print "Hi"
Community
  • 1
  • 1
thegrinner
  • 11,546
  • 5
  • 41
  • 64
  • will give two instance of `NameError: name 'self' is not defined` – Philipp Jul 20 '10 at 14:30
  • Good catch. Updated it so it worked correctly using IDLE and reposted that. – thegrinner Jul 20 '10 at 14:36
  • thanks for the answer. i am doing this way right now. but i think there must be some easier way to access parent class object. i found something like *im_self* but couldn't understand how to use it. – iamgopal Jul 20 '10 at 14:44
  • There is no such thing as a parent class object unless you pass it explicitly. How should an instance of `B` get access to an instance of `A` that is totally unrelated? – Philipp Jul 20 '10 at 15:11
  • You could change the part in class A to `def __init__(self, someB): self.b = someB(self)` – JAB Jul 20 '10 at 15:35
1

You have to pass the instance and store it in a member variable:

class B(object):
    def __init__(self, a):
        self.a = a
    def c(self):
        self.a.d()

class A(object):
    def __init__(self):
        self.b = B(self)
    def d(self):
        print "Hi"

Note that your code will give lots of errors due to missing self parameters.

Philipp
  • 48,066
  • 12
  • 84
  • 109