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 = 0insideDog, at the same indent asdef, withoutself.. - In
__init__, after setting the name, doDog.count += 1. UseDog.count, notself.count:self.count += 1would 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
RexandBuddyand prints the counter; then it createsMax, prints the counter and Max's name, createsLuna, 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)
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
