How to do nested class and inherit inside the class [closed]

☆樱花仙子☆ 提交于 2019-12-12 03:11:52

问题


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()

回答1:


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


来源:https://stackoverflow.com/questions/38778158/how-to-do-nested-class-and-inherit-inside-the-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!