1

I tried quite a few times, but didn't get the following codes work

Thanks in advance for any help/suggestions

class A(object):
    def __init__(self,x,y,z):
        self.c=C(x,y,z)
    def getxyz(self):
        return self.c.getxyz()

    class B(object):
        def __init__(self,x,y):
            self.x=x
            self.y=y
        def getxy(self):
            return self.x, self.y
    class C(B):
        def __init__(self,x,y,z):
            super(C,self).__init__(x,y)
            #self.x,self.y=x,y
            self.z=z
        def getxyz(self):
            (x,y)=self.getxy()
            return x,y,self.z
a=A(1,2,3)
a.getxyz()
george andrew
  • 451
  • 4
  • 12

1 Answers1

3

I'm not 100% sure why you're nesting classes (rarely is that what you actually want to do) but the line

self.c = C(x,y,z)

is almost certainly the problem here. Unless I don't understand what it is you're trying to accomplish (which may well be), you should be able to do

class A(object):

    def __init__(self, x, y, z):
        self.c = self.C(x,y,z)

    def getxyz(self):
        return self.c.getxyz()

    class B(object):

        def __init__(self, x, y):
            self.x = x
            self.y = y

        def getxy(self):
            return self.x, self.y

    class C(B):

        def __init__(self, x, y, z):
            super(A.C, self).__init__(x,y)
            self.z = z

        def getxyz(self):
            (x,y) = self.getxy()
            return x, y, self.z
Adam Smith
  • 52,157
  • 12
  • 73
  • 112
  • The "self.c" fix is correct - however , the empty "super()" call is Python3 only - the question is likely using Python2 - so `super` has to have parameters, and it is the other point where the OP code would break - it should be `super(A.C,self).__init__(x,y)` – jsbueno Aug 04 '16 at 22:26
  • (I did fix that, so that the code now will run) – jsbueno Aug 04 '16 at 22:27
  • @georgeandrew: please note that the part of "I'm not 100% sure why you're nesting classes " is part of the correctness of the answer :-) However this code will work. – jsbueno Aug 04 '16 at 22:29
  • Thank you all, it works as your suggestions. I am a newbie in python and try to practice the oop. I didn't get both place correct when I tried before. The nested class is for property hiding. and the inherit is for code re-use. But seems in python 2, the super()function has to add the parent class name as a predix, that makes the code a bit ugly, which is ok in python3. – george andrew Aug 04 '16 at 22:47
  • @georgeandrew Property hiding should be done using the `@property` decorator. [see this example](https://gist.github.com/anonymous/52c864b9ff05c00ca6a7c45c9a5c938d) – Adam Smith Aug 05 '16 at 19:20