-1

So I can't seem to figure out how to inherit the __init__ from my classes. I am trying to make an RPG by myself, and I just recently learned that using inheritance for making my enemies, characters and stuff like that was a better idea. So I started using it for enemies but ran into a problem with the init method. This is my Enemy Class:

class Enemy():
    def __init__(self, number_of, name):
        self.number_of = int(number_of)
        self.name = name
        self.hp = 20 * self.number_of
        self.dmg = 2 * self.number_of
    def attack(self, player):
        dmg = 0
        player.hp -= dmg
    def appearing(self):
        if self.number_of > 1:
            print (f"{self.number_of} {self.name}s have appeared")
        else:
            print(f"A {self.name} has appeared") 

And i tried different ways to make the specific enemy classes. I will just leave the methods, because they work fine for me, and focus in the init of my class. So first I tried doing it like this:

class Orc():
    def __init__(self):
        Enemy.__init__(self,number_of, name)

But Python makes it a type error: TypeError: init() takes 1 positional argument but 3 were given

I also tried putting self in front of number_of and name, but the same error came out.

Then I tried putting in arguments in the original init:

class Orc():
def __init__(self, number_of,name):
    Enemy.__init__(self,self.number_of, self.name)

But that just resulted in an Attribute error:

AttributeError: 'Orc' object has no attribute 'number_of'

I then tried putting self. in front of the init, but then there was a syntaxerror.

I just ended up doing different init for each class (each type of enemy), without even using the init in the parent (Enemy) class.

So what am I doing wrong, and what can I do instead, to actually use the init method in the parent class, and save some code

1 Answers1

2

First, you need to actually inherit from the Enemy class in your Orc class, then you can simply call super():

class Orc(Enemy):
    def __init__(self, number_of, name):
        super().__init__(number_of, name)

self is automatically passed to the class when you call super.

Lord Elrond
  • 13,430
  • 7
  • 40
  • 80