views:

67

answers:

2

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.

+1  A: 

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
+2  A: 

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"
thegrinner
will give two instance of `NameError: name 'self' is not defined`
Philipp
Good catch. Updated it so it worked correctly using IDLE and reposted that.
thegrinner
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
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
You could change the part in class A to `def __init__(self, someB): self.b = someB(self)`
JAB