传递给python 3的参数数目错误

2024-09-28 21:08:52 发布

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

我有一个类,有2到3个参数,但当我通过1它说只有1已通过,但当我通过2它说4已通过。你知道吗

代码:

class GiantWarren(Warren):
  def __init__(self, Variability, RabbitCount):
     self.__MAX_RABBITS_IN_WARREN = 200
     super(GiantWarren, self).__init__(Variability, RabbitCount, self.__MAX_RABBITS_IN_WARREN)
     self.__RabbitCount = RabbitCount

  def NeedToCreateNewWarren(self):
    if self.__RabbitCount == self.__MAX_RABBITS_IN_WARREN:
      return True
    else:
      return False

它被称为:

self.__Landscape[11][4].GiantWarren = GiantWarren(self.__Variability, 115)

给出错误

super(GiantWarren, self).init(Variability, RabbitCount, self.MAX_RABBITS_IN_WARREN) TypeError: __init() takes from 2 to 3 positional arguments but 4 were given

class Warren: def __init__(self, Variability, RabbitCount = 0): self._MAX_RABBITS_IN_WARREN = 99 self._RabbitCount = RabbitCount self._PeriodsRun = 0 self._AlreadySpread = False self._Variability = Variability

Tags: inselffalsereturninitdefmaxclass
2条回答

在从类GiantWarren调用超类时,您做到了:

super(GiantWarren, self).__init__(Variability, RabbitCount, self.__MAX_RABBITS_IN_WARREN)

例如,使用了4个参数(请注意,当前实例即self是隐式传递的)。你知道吗

但是类Warren的构造函数有签名:

def __init__(self, Variability, RabbitCount = 0):

也就是说,它需要3个参数,包括第一个实例。另外两个参数中,一个是位置参数(强制),另一个是带有默认值的关键字(可选)。你知道吗

因此,从命名来看,super调用中的self.__MAX_RABBITS_IN_WARREN参数是多余的。如果不是,你自己解决。你知道吗


另外,请尝试遵循PEP-8,将类命名为CamelCase,函数/变量命名为snake\u case。你知道吗

通过GiantWarren传入的参数太多。传递4个参数(包括self):

super(GiantWarren, self).__init__(Variability, RabbitCount, self.__MAX_RABBITS_IN_WARREN)

。。。Warren的构造器最多取3个,包括self:

def __init__(self, Variability, RabbitCount = 0):

相关问题 更多 >