VaySticy VaySticy - 1 month ago 7
Python Question

Where did it go wrong in my code?

class Player:
def __init__(self):
self.speed
self.hp
def Berserker(self):
self.speed == 12
self.hp == 6

print("Berserkers stats are: " + Berserker())


So, What have I done wrong? As you can see, I'm very new to Python.
The error I'm getting is: TypeError: Berserker() missing 1 required positional argument: 'self'

Answer

You're missing quite a few things, but I'll help you out!

Your __init__ function doesn't do anything. Let's give it some base stats. I'll say that a Player's default speed and health will be 10 and 100, respectively. Then we'll make Berserker a subclass of Player (I think that's what you were going for?). And lastly, I'll give Player a method that will allow you to get a string-formatted output for its values.

First, the new Player:

class Player:
    def __init__(self, speed=10, health=100):
        self.speed = speed
        self.health = health

    def __str__(self):
        return "A player with speed {} and health {}.".format(self.speed, self.health)

And now for the Berserker. I'll give it a base speed of 15 and health of 85. (Obviously the specifics are up to you!)

class Berserker(Player):
    def __init__(self):
        super().__init__(speed=15, health=85)

Lastly, we can create these and print the value. I'll make a couple different versions so you can see how it works. (And I'll use the regular Python interpreter for this).

>>> p1 = Player()
>>> p2 = Player(7, 120)
>>> b = Berserker()
>>> print(p1)
A player with speed 10 and health 100.
>>> print(p2)
A player with speed 7 and health 120.
>>> print(b)
A player with speed 15 and health 85.

Hopefully this gives you a good place to start!

Comments