Python继承与sup

2024-09-28 03:15:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个文件,每个文件都有不同的类。我第一节课的代码如下:

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

    def getX(self):
        return self.x

    def printInfo(self):
        print self.x,",",self.y

现在我有一个类Pixel继承自Point:

from fileA import Point

class Pixel(Point):
    def __init__(self,x,y,color):
        #Point.__init__(self,x,y)     //works just fine
        super(Pixel,self).__init__()
        self.color=color

    def printInfo(self):
        super(Pixel,self).printInfo()
        print self.color

因此,正如您所看到的,Pixel继承自Point,它覆盖了printInfo方法。我这里有两个问题,第一个是在Pixel的构造函数中,被注释的行可以正常工作,但是带有super的版本会抛出一个错误。另外,当我想从printInfo方法调用基类的printInfo时,它会抛出另一个错误。我的问题是,如何在构造函数和重写方法中同时使用super,以便它工作?你知道吗

我使用的是python2.7,错误是TypeError:必须是type,而不是classobj

谢谢


Tags: 文件方法代码selfinitdef错误class
1条回答
网友
1楼 · 发布于 2024-09-28 03:15:54

首先,您只能对新样式类使用super,但是Point当前是一个旧样式类。要使其成为新样式类,它必须从object继承:

class Point(object):
    def __init__(self,x,y):
        self.x=x
        self.y=y

    def getX(self):
        return self.x

    def printInfo(self):
        print self.x,",",self.y

其次,您必须传递Point.__init__在使用super调用它时所期望的参数,就像您直接使用Point.__init__(self,...)一样:

class Pixel(Point):
    def __init__(self,x,y,color):
        super(Pixel,self).__init__(x, y)  # Don't forget x,y
        self.color=color

    def printInfo(self):
        super(Pixel,self).printInfo()
        print self.color

相关问题 更多 >

    热门问题