传递python 3的参数数量错误

时间:2018-02-21 17:51:04

标签: python class

我有一个有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 ()需要2到3个位置参数,但是给出了4个

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

2 个答案:

答案 0 :(得分:1)

在调用类GiantWarren中的超类时,你做了:

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

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

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

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

即。它需要3个参数,包括实例作为第一个。在另外两个参数中,一个参数是位置(强制),另一个是具有默认值的关键字(可选)。

因此,从命名看来,self.__MAX_RABBITS_IN_WARREN调用中的super参数是多余的。如果没有,请按照自己的方式修复。

顺便说一下,请尝试按照PEP-8,将您的类 CamelCase 和函数/变量命名为 snake_case

答案 1 :(得分:0)

您通过GiantWarren传递了太多参数。你传递了4个参数(包括self):

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

......而Warren的构造函数最多包含3个,包括self:

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

相关问题