python , how to find class object from child entity?
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.
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"
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.
精彩评论