TypeError: Super does not take Key word arguments?

2019-03-15 04:56发布

First, here is my code:

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

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__).

2条回答
在下西门庆
2楼-- · 2019-03-15 05:20

Option # 1 : Python 2.7x

Here you can pass self keywork to super() which inherently refers the instance properties.

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

Option # 2 : Python 3x

super() no longer need to any parameters and you can simply write

super().__init__("The Kidnappers", 30, 7)
查看更多
Deceive 欺骗
3楼-- · 2019-03-15 05:24

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)

All you pass to super() is the child class (Kidnappers in this case) and a reference to the current instance (self).


Note however that if you are using Python 3.x, all you need to do is:

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

and Python will work out the rest.


Here are some links to where this is explained in the documentation:

查看更多
登录 后发表回答