[英]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.