TypeError:Super不接受关键字参数? [英] TypeError: Super does not take Key word arguments?
问题描述
首先,这是我的代码:
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__()
当我对此进行编译时,出现此错误:
When I compile this I get this error:
super(WildBoar, name="Wild Boar", hp=10, damage=2).__init__()
TypeError: super does not take keyword arguments
我试图四处寻找帮助,但找不到任何东西。在其他班级的超级赛中,我也有一些克瓦格,但这些都是提出任何问题的人(截至目前)。那么是什么原因造成的呢?我还看到有人说在基类中放置 super
可以解决该问题,但是没有用(我传入了与Base中相同的参数类的 __ init __
)。
I tried looking around for any kind of help but I couldn't find anything. I also have some Kwargs in some other class's supers, but these are the ones raising any kind of issues (as of right now). So what could be causing this? I've also seen someone say that putting a super
in the base class will fix it, but it didn't work (I passed in the same arguments that are in the Base class's __init__
).
推荐答案
父级<$ c的参数$ c> __ init __ 方法应传递给 __ init __
方法:
The arguments to the parent's __init__
method should be passed to the __init__
method:
super(Kidnappers, self).__init__(name="The Kidnappers", hp=30, damage=7)
# or
super(Kidnappers, self).__init__("The Kidnappers", 30, 7)
所有传递给 super( )
是子类(在这种情况下为 Kidnappers
),是对当前实例的引用( self
)。
All you pass to super()
is the child class (Kidnappers
in this case) and a reference to the current instance (self
).
但是请注意,如果您使用的是Python 3.x,则需要做的是:
Note however that if you are using Python 3.x, all you need to do is:
super().__init__("The Kidnappers", 30, 7)
,其余部分将由Python处理。
and Python will work out the rest.
这是在文档中对此解释的一些链接:
Here are some links to where this is explained in the documentation:
- Python 2.x
super()
- Python 3.x
super()
这篇关于TypeError:Super不接受关键字参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!