【问题标题】:Python child class initialiser argumentPython 子类初始化参数
【发布时间】:2016-10-12 09:07:30
【问题描述】:

我有一个父类,它的初始化器有三个参数,现在我想要一个子类,它的初始化器只有两个参数,但它告诉我在尝试创建子对象时必须给它三个参数。

class Parent(Exception):
    def _init_(self, a, b):
    ...
    super(Parent, self)._init_(a, b)

class Child(Parent):
    def _init_(self, b):
        super(Child, self)._init_(123, b)

# somewhere in the code I have:
raise Child("BAD_INPUT")

我要做的是用一个参数实例化一个 Child 对象,然后在该 Child 对象的初始化程序中调用 Parent 的初始化程序并传入两个参数,一个是硬编码的 (123)。

我得到的错误: TypeError: __init__() takes exactly 3 arguments (2 given)

【问题讨论】:

  • _init_ -> __init__?
  • 当我运行此代码并修复 super(Parent, self)._init_(a, b) 上的缩进时,除了你提出的那个之外,我没有任何例外
  • 天啊!!!我在这上面浪费了几个小时,__ 真的是个问题!! Python应该给我一个更好的错误信息.. T T

标签: python inheritance initialization


【解决方案1】:

你应该可以使用:

class Parent(Exception):
    def __init__(self, a, b):
        self.a = a
        self.b = b

class Child(Parent):
    a = 123
    def __init__(self, b):
        super().__init__(self.a, b)

【讨论】:

  • 没有__super__ 这样的东西。问题在于_init_ 缺少额外的下划线,您的答案无法解决
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-06-10
  • 1970-01-01
  • 2020-03-16
  • 2016-11-21
  • 1970-01-01
  • 2015-10-01
  • 1970-01-01
相关资源
最近更新 更多