如何做嵌套类并在类内部继承 [英] How to do nested class and inherit inside the class

查看:138
本文介绍了如何做嵌套类并在类内部继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了很多次,但是以下代码无法正常工作

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

推荐答案

我不是100%知道为什么要嵌套类(很少是您真正想做的事情),而是行

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

这篇关于如何做嵌套类并在类内部继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆