super() 在 Python 2 中给出错误
super() gives an error in Python 2
刚开始学习Python,不太明白这段代码的问题出在哪里。我有一个基础 class Proband,有两种方法,我想创建一个 subclass Gesunder,我想覆盖属性 idn,artefakte。
import scipy.io
class Proband:
def __init__(self,idn,artefakte):
self.__idn = idn
self.artefakte = artefakte
def getData(self):
path = 'C:\matlab\EKGnurbild_von Proband'+ str(self.idn)
return scipy.io.loadmat(path)
def __eq__(self,neueProband):
return self.idn == neueProband.idn and self.artefakte == neueProband.artefakte
class Gesunder(Proband):
def __init__(self,idn,artefakte,sportler):
super().__init__(self,idn,artefakte)
self.__sportler = sportler
hans = Gesunder(2,3,3)
在Python2中,super()
本身是无效的。相反,您必须使用 super(ClassName, self)
.
super(Gesunder, self).__init__(self, idn, artefakte)
super()
调用应修改为:
super(Gesunder, self).__init__(self, idn, artefakte)
您的代码有 2 个问题。在 python 2:
super()
接受 2 个参数:class 名称和实例
- 为了使用
super()
,基础 class 必须继承自 object
因此您的代码变为:
import scipy.io
class Proband(object):
def __init__(self,idn,artefakte):
self.__idn = idn
self.artefakte = artefakte
def getData(self):
path = 'C:\matlab\EKGnurbild_von Proband'+ str(self.idn)
return scipy.io.loadmat(path)
def __eq__(self,neueProband):
return self.idn == neueProband.idn and self.artefakte == neueProband.artefakte
class Gesunder(Proband):
def __init__(self,idn,artefakte,sportler):
super(Gesunder, self).__init__(idn,artefakte)
self.__sportler = sportler
hans = Gesunder(2,3,3)
请注意,对 super(Gesunder, self).__init__
的调用没有将 self
作为第一个参数。
刚开始学习Python,不太明白这段代码的问题出在哪里。我有一个基础 class Proband,有两种方法,我想创建一个 subclass Gesunder,我想覆盖属性 idn,artefakte。
import scipy.io
class Proband:
def __init__(self,idn,artefakte):
self.__idn = idn
self.artefakte = artefakte
def getData(self):
path = 'C:\matlab\EKGnurbild_von Proband'+ str(self.idn)
return scipy.io.loadmat(path)
def __eq__(self,neueProband):
return self.idn == neueProband.idn and self.artefakte == neueProband.artefakte
class Gesunder(Proband):
def __init__(self,idn,artefakte,sportler):
super().__init__(self,idn,artefakte)
self.__sportler = sportler
hans = Gesunder(2,3,3)
在Python2中,super()
本身是无效的。相反,您必须使用 super(ClassName, self)
.
super(Gesunder, self).__init__(self, idn, artefakte)
super()
调用应修改为:
super(Gesunder, self).__init__(self, idn, artefakte)
您的代码有 2 个问题。在 python 2:
super()
接受 2 个参数:class 名称和实例- 为了使用
super()
,基础 class 必须继承自object
因此您的代码变为:
import scipy.io
class Proband(object):
def __init__(self,idn,artefakte):
self.__idn = idn
self.artefakte = artefakte
def getData(self):
path = 'C:\matlab\EKGnurbild_von Proband'+ str(self.idn)
return scipy.io.loadmat(path)
def __eq__(self,neueProband):
return self.idn == neueProband.idn and self.artefakte == neueProband.artefakte
class Gesunder(Proband):
def __init__(self,idn,artefakte,sportler):
super(Gesunder, self).__init__(idn,artefakte)
self.__sportler = sportler
hans = Gesunder(2,3,3)
请注意,对 super(Gesunder, self).__init__
的调用没有将 self
作为第一个参数。