What is a class attribute
Most attributes in Python belong to one object. Assigning self.name = name inside __init__ stores a separate name on each Dog. Other languages call data shared by all objects of a class a "static member". In Python it is a class attribute: a variable written directly in the class body, at the same indent as def, without self..
There is one copy of a class attribute, and you read it through the class name, as in Dog.count. That makes it the natural place for a counter: a number that describes all dogs together rather than a single dog.
Contrast this with an instance attribute. If every dog stored its own count, each one would only know about itself, and nothing could add them up. A class attribute gives the class a single place to keep information about all of its objects, and each object can still read it. It is also available before any object exists, which is why Dog.count can be asked for with no dog at all.
The exercise
The lesson starts with a Dog class that only stores its name. The goal is to count how many Dog objects have been created, with one counter shared by all of them. The program below the class creates Rex and Buddy, prints the counter, creates Max, prints the counter and Max's name, creates Luna and prints the counter once more. Those lines must not change, and the expected output is:
2
3
Max
4
Step by step
- Inside
Dog, above__init__, addcount = 0. Written in the class body and not onself, it belongs to the class itself, so it exists before any dog does and starts at 0. - At the end of
__init__, addDog.count += 1. Every time a dog is created,__init__runs once, so the counter grows by exactly one, whatever the dog's name is.
The solution in Python
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)
The output is the expected one: 2, then 3, then Max, then 4. The last dog, Luna, is never stored in a variable, but creating it still runs __init__, so it is counted.
Why Dog.count and not self.count
This is the main trap. Reading self.count works, because Python looks for the name on the object first and then on its class. With the solution above, rex.count and buddy.count both give 4 after four dogs exist, and the object's own dictionary, rex.__dict__, holds only {'name': 'Rex'}.
Writing self.count += 1 behaves differently. The statement reads the class value, adds one, and then assigns the result to self.count. An assignment through self always creates or updates an attribute on that object, not on the class. With this version of __init__, after two dogs the numbers are:
class Bad:
count = 0
def __init__(self, name):
self.name = name
self.count += 1
a = Bad("Rex")
b = Bad("Buddy")
print(Bad.count, a.count, b.count)
print(a.__dict__)
0 1 1
{'name': 'Rex', 'count': 1}
The class counter stays at 0, and each dog got its own private count of 1. Naming the class in Dog.count += 1 updates the one shared variable.
The rule to remember: reading a name goes from the object to its class, but assigning to self.something always writes on the object. To change shared data, assign through the class.
Static methods
Python also has @staticmethod, for a function that lives inside the class but needs neither an instance nor the class, so it takes no self. It is called through the class name too. This lesson only needs the attribute, but a short example shows the idea:
class Dog:
count = 0
@staticmethod
def describe(n):
return "dogs: " + str(n)
print(Dog.describe(3))
It prints dogs: 3.
Where the counting happens
The counter is updated inside __init__ because that method runs exactly once per object, at the moment it is created. Putting Dog.count += 1 anywhere else, for example in a method the caller has to remember to call, would let the count drift away from the number of dogs. It goes at the end of __init__, after self.name = name, but its position among the lines of __init__ does not change the result here.
The body of Dog runs once, when Python reads the class definition. That is when count = 0 is executed, so the counter is reset only by running that line again, never by creating dogs.
Edge cases and key takeaways
- A class attribute is declared in the class body, with no
self., and there is one copy shared by all objects. - Read it and change it through the class name:
Dog.count. self.count += 1creates a separate instance attribute and leaves the shared counter unchanged.- If the attribute were missing,
Dog.countwould fail withAttributeError: type object 'Dog' has no attribute 'count', which is what the starter code produces before the first step. - The counter goes up for every object created, including ones that are not stored in a variable.
