← All lessons

Class attributes

Sign in · Sign up

Lesson 10.4

A class attribute is declared right in the body of the class, outside __init__. There is one for all objects:

class Hero:
    count = 0

    def __init__(self, name):
        self.name = name
        ...                    # a shared counter

Hero("Mia")
Hero("Timur")

print(Hero.count)
  • count = 0 belongs to the class, while self.name belongs to a particular object;
  • a shared counter must be changed through the class: Hero.count += 1;
  • self.count += 1 would create the object's own count and leave the shared one alone;
  • Hero.count and hero.count show the same thing until the object makes its own.

The check gives the list of names names. Create a hero for each name and print how many heroes there are in total: Total heroes: <count>.

Hint

The counter is declared in the body of the class, outside __init__.

It must be increased through the class name: Hero.count += 1. Through self.count the object gets a separate field and the shared counter does not change.