[英]Python inheritance with super
我有两个文件,每个文件都有不同的类。 我的第一堂课的代码如下:
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
现在我有一个从Point继承的Pixel类:
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,以便它可以正常工作?
我正在使用python 2.7,错误是TypeError:必须是类型,而不是classobj
谢谢
首先,您只能将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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.