TypeError:Super不接受关键字参数?

时间:2015-06-04 02:20:38

标签: python class inheritance super

首先,这是我的代码:

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

我试着寻找任何帮助,但我找不到任何东西。我也有一些Kwarg在其他一些级别的超级,但这些是提出任何问题的人(截至目前)。那可能是什么导致了这个?我也看到有人说在基类中放一个super会修复它,但它没有用(我传入了基类中的相同参数) __init__)。

2 个答案:

答案 0 :(得分:17)

父项__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将解决剩下的问题。

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

答案 1 :(得分:-2)

选项#1:Python 2.7x

在这里,您可以将self keywork传递给super(),而super()本身就是指实例属性。

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

选项#2:Python 3x

super() 不再需要任何参数,您只需编写

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