【问题标题】:Wrong number of arguments passed python 3错误数量的参数传递了python 3
【发布时间】:2018-02-21 17:51:04
【问题描述】:

我有一个有 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(可变性, 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

【问题讨论】:

  • 添加类Warren的代码。
  • 那是 __init__()Warren 被三个参数调用 (+ self)
  • 哦,更改您的命名约定。你不会在 python 中命名这样的东西。
  • @HuStmpHrrr 虽然通常建议,但不一定要遵循 PEP8。
  • @byxor 没有必要的约定。但是,我确实认识到与社区准则保持一致的重要性。

标签: python class


【解决方案1】:

在从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_case

【讨论】:

    【解决方案2】:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 2022-11-14
      • 1970-01-01
      • 1970-01-01
      • 2015-10-10
      • 2011-02-20
      • 1970-01-01
      • 2014-12-18
      • 2021-08-01
      • 1970-01-01
      相关资源
      最近更新 更多