2

New python learner here, when i was watching some tutorials i stumbled upon a code like this:

from character import *


class enemy(Character):
    def __init__(self, name, hp, str)
        Character.__init__(self, name, hp)

What exactly does the following code do in this case? First time seeing multiple _init _in a single class and i can't seem to understand this type of code.

Character.__init__(self, name, hp)

the character file code is here:

class Character(object):

def __init__(self, name, hp):
    self.name = name
    self.hp = hp
def attack(self,other):
    pass
pythonsohard
  • 127
  • 9

2 Answers2

3

It's calling the constructor of the enemy classes' superclass, Character. When a class (like enemy) inherits from a class (in this case Character) it needs to ensure that the superclass is set up correctly, and thus needs to call __init__ on the superclass.

Update: there's actually two ways to call the constructor of a superclass - as you've posted above and with the super function. Rather than reposting something that's been discussed many times, I'll direct you to this answer.

Community
  • 1
  • 1
elhefe
  • 3,404
  • 3
  • 31
  • 45
3

When enemy defines its own __init__ method, it overwrites the one on the Character class. Therefore, when you use enemy(), the __init__ method that was defined for the Character class is not called. To make sure that it is called anyway, the __init__ method in enemy calls it itself. The __init__ method that was defined in Character is still an instance method, but it is hidden by the new __init__ method that took its place. If you say self.__init__(), it is a shortcut for enemy.__init__(self). In this case, we don't want to call the enemy __init__ method; we want to call the Character __init__ method, so we don't use self.__init__(). Instead of using the shortcut that is often used, we instead call the Character __init__ method directly with Character.__init__(self). As @kevin mentioned in a comment on another post, it is common to use the super() function here:

super().__init__() # In Python3, or
super(enemy, self).__init__() # In Python2
zondo
  • 19,901
  • 8
  • 44
  • 83