我有两个文件,每个文件都有不同的类。我第一节课的代码如下:
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
谢谢
首先,您只能对新样式类使用
super
,但是Point
当前是一个旧样式类。要使其成为新样式类,它必须从object
继承:其次,您必须传递
Point.__init__
在使用super
调用它时所期望的参数,就像您直接使用Point.__init__(self,...)
一样:相关问题 更多 >
编程相关推荐