Start learning free

LESSON 397 OF 410 · OBJECT-ORIENTED PROGRAMMING

Static Members in Python in Python

Practice

TL;DR:

A class attribute is declared at the class level (no self.). There is one copy, shared by every Dog, and you read it through the class name: Dog.count. Python also has @staticmethod for functions that live in the class but need no instance (no self); this lesson only needs the attribute.

You start with:

class Dog:
    def __init__(self, name):
        self.name = name

Your task: count how many Dog objects have been created, with one counter shared by all of them.

  • Add a class attribute count = 0 inside Dog, at the same indent as def, without self..
  • In __init__, after setting the name, do Dog.count += 1. Use Dog.count, not self.count: self.count += 1 would create a separate instance attribute and leave the shared counter at 0.
  • The counter starts at 0 before any dog exists, and goes up by exactly 1 for every dog created, whatever its name.
  • The program that is already in the editor creates Rex and Buddy and prints the counter; then it creates Max, prints the counter and Max's name, creates Luna, and prints the counter once more. Do not change those lines.

Expected output:

2
3
Max
4

Read the counter with Dog.count. It starts at 0 and goes up by one for every Dog(...).

class Dog:
    count = 0

    def __init__(self, name):
        self.name = name
        Dog.count += 1

rex = Dog("Rex")
buddy = Dog("Buddy")
print(Dog.count)
max_dog = Dog("Max")
print(Dog.count)
print(max_dog.name)
Dog("Luna")
print(Dog.count)

STEP 1 OF 2
    Ctrl + Enter to check

    Static Members in Python

    Keep going with PythonAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free