【问题标题】:TypeError: Super does not take Key word arguments?TypeError:Super 不接受关键字参数?
【发布时间】:2015-08-18 11:27:22
【问题描述】:

首先,这是我的代码:

class Enemy():
    def __init__(self, name, hp, damage):
        self.name = name
        self.hp = hp
        self.damage = damage


    def is_alive(self):
        """Checks if alive"""
        return self.hp > 0

class WildBoar(Enemy):
    def __init__(self):
        super(WildBoar, name="Wild Boar", hp=10, damage=2).__init__()

class Marauder(Enemy):
    def __init__(self):
        super(Marauder, name="Marauder", hp=20, damage=5).__init__()


class Kidnappers(Enemy):
    def __init__(self):
        super(Kidnappers, name="The Kidnappers", hp=30, damage=7).__init__()

当我编译这个我得到这个错误:

super(WildBoar, name="Wild Boar", hp=10, damage=2).__init__()
TypeError: super does not take keyword arguments

我试图四处寻找任何帮助,但找不到任何东西。我在其他班级的超人中也有一些 Kwargs,但这些都是引发任何问题的人(截至目前)。那么可能是什么原因造成的呢?我还看到有人说在基类中添加super 可以解决它,但它不起作用(我传递了与基类__init__ 中相同的参数)。

【问题讨论】:

    标签: python class inheritance super


    【解决方案1】:

    父类的__init__ 方法的参数应该传递给__init__ 方法:

    super(Kidnappers, self).__init__(name="The Kidnappers", hp=30, damage=7)
    # or
    super(Kidnappers, self).__init__("The Kidnappers", 30, 7)
    

    您传递给super() 的只是子类(在本例中为Kidnappers)和对当前实例的引用(self)。


    但是请注意,如果您使用的是 Python 3.x,您只需:

    super().__init__("The Kidnappers", 30, 7)
    

    Python 会解决剩下的问题。


    以下是文档中解释的一些链接:

    【讨论】:

      【解决方案2】:

      选项 #1:Python 2.7x

      在这里,您可以将 self 密钥传递给 super(),它固有地引用实例属性。

      super(self, name="Wild Boar", hp=10, damage=2).__init__()
      

      选项 #2:Python 3x

      super()不再需要任何参数,你可以简单地写

      super().__init__("The Kidnappers", 30, 7)
      

      【讨论】:

      • 选项 #1 仍在将 __init__ 的参数传递给 super,这将与 Scoutdrago3 已经经历的方式完全相同。
      猜你喜欢
      • 2022-01-24
      • 1970-01-01
      • 1970-01-01
      • 2016-09-01
      • 2021-09-24
      • 2018-11-22
      • 2012-07-27
      • 1970-01-01
      相关资源
      最近更新 更多