← All lessons

__init__: data at creation

Sign in · Sign up

Lesson 10.1

An empty class has no data. __init__ helps set it at creation:

class Hero:
    def __init__(self, name, hp):
        self.name = name
        self.hp = hp

hero = Hero("Mia", 100)
  • __init__ is the constructor: Python calls it itself when you write Hero(...);
  • self is always the first parameter, and Python fills it in (more in lesson 10.2);
  • self.name = name saves the value into the object, while self.name == name would just compare two values;
  • after creation the data is reached with a dot: hero.name and hero.hp.

The check gives the list heroes — pairs of "name and HP". Create a hero Hero(...) for each pair and, when printing, take the name and health from the object: <name>: <hp> HP.

Hint

The order of the parameters in __init__ sets the order of the arguments.

Inside the constructor each value is saved into the object with self. When printing, take the name and HP from the object: hero.name, hero.hp.