← All lessons

self: this object

Sign in · Sign up

Lesson 10.2

self is the object itself on which the method was called:

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

    def hit(self, points):
        ...                    # lower the HP and print a line

hero1 = Hero("Anna", 90)
hero2 = Hero("Leo", 60)

hero1.hit(25)
hero2.hit(25)
  • in hero1.hit(10) Python passes the object hero1 as the first argument itself — you never pass self by hand;
  • self.hp -= points changes the HP of this very hero: hero2 has its own self and its own HP;
  • that's why the same method behaves differently on two objects.

The check gives the list of heroes heroes — triples of "name, HP, damage". Create an object for each triple, hit it and print <name>: <hp> HP left.

Hint

self is the object the method was called on; Python passes it itself.

The method changes the data of this very object: the HP drops by the given number. Then print the name and the remaining HP — through self.