0

What's the best way of having a child class (B) instance call one of its parent class (A) instance's methods? Passing self into the instance of the child class (B) seems to work, but somehow that doesn't seem to be efficient or good practice. Any better ways of going about this?

class A():
    def __init__(self,name):
        self.instanceOfB = self.B(self)
        self.name = name

    def hello(self):
        print 'Hello '+self.name

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

        def hi(self):
            self.parent.hello() ##Call parent instance's method 'hello()' here

instanceOfA = A('Bob')
instanceOfA.instanceOfB.hi()

Should result in:

Hello Bob

@classmethod and @staticmethod only work if A.hello() does not depend on any information instantiated with class A

SkyNT
  • 718
  • 1
  • 8
  • 19
  • Just out of curiosity, why are you nesting classes? – Blender Feb 22 '13 at 10:47
  • Just a way of organizing objects, I guess? Besides limiting B being instantiated in A only, is there a difference between that and `class B(A)` that I am missing? – SkyNT Feb 22 '13 at 10:53
  • I thought it was just an indentation error, and then I saw `self.instanceOfB = self.B(self)` – entropy Feb 22 '13 at 10:53
  • 1
    `class B(A)` means that class B *inherits* from class A. Ie, that iy has the same methods/properties and can optionally override some of them or extend them with further functionality. Nesting classes means that each instance of class A has its own version of class B(not its own instance object of class B, but its own version of the class itself) – entropy Feb 22 '13 at 10:55
  • This is extremely poor design, not in any way related to OOD techniques. Don't try to fix it, but use a proper OO design instead! – Ber Feb 22 '13 at 10:57
  • @entropy that much I understand. But I want B to call the method of _instance_ A. – SkyNT Feb 22 '13 at 11:00
  • @SkyNT the answer and the "right" way to do it depends on whether you actually want `B` to inherit from `A`, or whether then are truly different classes. – YXD Feb 22 '13 at 11:05
  • @Mr E In my current case, A holds data as well as methods to operate on the data. B Holds data _about_ the data in A in such a way that it must also instruct A to call a method according to certain conditions. – SkyNT Feb 22 '13 at 11:12
  • @SkyNT see this question/answer: http://stackoverflow.com/questions/1765677/python-nested-classes-scope In python nesting classes does not imply any special relationship between them. You're better off not nesting and passing an instance of A to B's constructor(as you're already doing anyway) – entropy Feb 22 '13 at 11:16

0 Answers0