super()在Python 2中出错

2024-06-16 14:50:16 发布

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

我刚开始学习Python,我不太明白代码中的问题在哪里。我有一个带有两个方法的基类Proband,我想创建一个子类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)

Tags: path代码ioselfreturninitdefscipy
3条回答

super()调用应修改为:

super(Gesunder, self).__init__(self, idn, artefakte)

你的代码有两个问题。在python 2中:

  1. super()有两个参数:类名和实例
  2. 为了使用super(),基类必须从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作为第一个参数。你知道吗

在python2中,super()本身是无效的。相反,您必须使用super(ClassName, self)。你知道吗

super(Gesunder, self).__init__(self, idn, artefakte)

相关问题 更多 >