Sub topic 3
Instance attributes and class attributes
This chapter assumes you can write a class with __init__ and self, and that you know how lists and dictionaries behave when two names point to the same object. It explains where an attribute is stored, how Python finds it, and why a mutable class attribute is a common bug.
Where attributes live
Python stores attributes in dictionaries. Each instance has its own dictionary, __dict__. Each class has one too. An attribute assigned through self goes into the instance's dictionary. A name bound in the class body goes into the class's dictionary.
class Dog:
species = "Canis familiaris" # class attribute
def __init__(self, name, age):
self.name = name # instance attributes
self.age = age
rex = Dog("Rex", 3)
print(rex.__dict__) # {'name': 'Rex', 'age': 3}
print("species" in Dog.__dict__) # True
print("species" in rex.__dict__) # False
print(rex.species) # Canis familiarisrex.species works even though species is not in rex.__dict__. Python looks in the instance first, finds nothing, and then looks in the class. There is only one copy of species, and every Dog reads it.
- An instance attribute belongs to one object. Use it for data that differs between objects, such as a name or an age.
- A class attribute belongs to the class and is visible through every instance. Use it for constants, defaults, and counters.
How lookup works
When you read obj.name, Python checks these places in order:
- A data descriptor on the class (for example a property, covered in a later chapter).
- The instance's
__dict__. - The class, then its parents in method resolution order. This covers plain class attributes, and methods too, because methods are class attributes.
If none of them has the name, Python raises AttributeError.
Reading and writing follow different rules, and the rest of the chapter depends on that difference. Reads search the instance and then the class. Writes through an instance, as in obj.name = value, always go to the instance's __dict__. They never change the class attribute.
Shadowing: assigning through an instance
Because writes go to the instance, assigning to a name that exists on the class creates a new instance attribute with the same name. The instance attribute shadows the class attribute for that one object.
class Dog:
species = "Canis familiaris"
rex = Dog()
rex.species = "Canis lupus"
print(rex.species) # Canis lupus
print(Dog.species) # Canis familiaris (unchanged)
del rex.species # remove the instance attribute
print(rex.species) # Canis familiaris (class value visible again)To change the value for every instance, assign through the class: Dog.species = "...". Instances that have not shadowed the name see the new value right away. Instances that have shadowed it keep their own value.
a, b = Dog(), Dog()
a.species = "custom"
Dog.species = "changed"
print(a.species, b.species) # custom changedMethods follow the same rule. A function defined in the class is a class attribute, so assigning rex.describe = something hides the method on that one object. This is rarely what you want, and it explains some confusing bugs where a method "stops working" after a typo like self.describe = ....
The augmented assignment trap
An augmented assignment such as self.count += 1 is a read followed by a write. It expands to self.count = self.count + 1. The read finds the class attribute. The write creates an instance attribute.
class Counter:
count = 0
def bump(self):
self.count += 1
c1 = Counter()
c1.bump()
c1.bump()
print(c1.count) # 2
print(Counter.count) # 0
print(c1.__dict__) # {'count': 2}The class counter never moved. Each instance silently created its own count. To keep a counter shared by all instances, write through the class. Using type(self) keeps the code correct for subclasses.
class Counter:
count = 0
def __init__(self):
type(self).count += 1
Counter()
Counter()
print(Counter.count) # 2Be aware that type(self).count += 1 in a subclass reads the parent's value and then writes a new attribute on the subclass. After that, the parent and subclass counters are separate. If you need a single counter for a whole hierarchy, name the class explicitly, for example Counter.count += 1.
The shared mutable class attribute bug
The shadowing rules produce a well-known bug when the class attribute is mutable. A list, dict, or set defined in the class body is one object. Every instance that does not shadow it sees that same object. Calling append mutates the shared object. It performs no assignment, so no instance attribute is ever created.
class Basket:
items = [] # shared by every instance: a common bug
def add(self, item):
self.items.append(item)
class FixedBasket:
def __init__(self):
self.items = [] # a new list for each instance
def add(self, item):
self.items.append(item)
a, b = Basket(), Basket()
a.add("apple")
print(b.items) # ['apple']
c, d = FixedBasket(), FixedBasket()
c.add("apple")
print(d.items) # []The rule is to create per-instance containers in __init__. The += operator on a list adds a further wrinkle. self.items += ["pear"] first extends the shared list in place, because list.__iadd__ mutates it. It then assigns the result to self.items, which creates an instance attribute pointing at the same shared list. The bug is still there, and the instance now has a misleading items entry in its __dict__.
Immutable class attributes (numbers, strings, tuples, None) are safe as defaults. You cannot change them in place, so any "change" is an assignment, and an assignment through an instance only shadows the value.
Choosing where an attribute belongs
| Kind of data | Put it in | Example |
|---|---|---|
| Differs per object | `__init__` via `self` | `self.name = name` |
| Same for all objects, read-only | Class body | `species = "Canis familiaris"` |
| Immutable default that may be overridden per object | Class body | `timeout = 30` |
| Shared state that all objects update | Class body, written via the class | `Counter.count += 1` |
| Per-object list, dict, or set | `__init__` | `self.items = []` |
An immutable class attribute works well as an overridable default. Instances that need a different value assign their own, and everyone else reads the class value. This saves memory when most objects use the default, because only the exceptions store anything.
class Connection:
timeout = 30 # default for every connection
def __init__(self, host, timeout=None):
self.host = host
if timeout is not None:
self.timeout = timeout # per-instance override
fast = Connection("a.example", timeout=5)
normal = Connection("b.example")
print(fast.timeout, normal.timeout) # 5 30
print(fast.__dict__) # {'host': 'a.example', 'timeout': 5}
print(normal.__dict__) # {'host': 'b.example'}Inspecting attributes
Three tools help when you are unsure where a value lives.
vars(obj)returnsobj.__dict__, the instance's own attributes only.vars(type(obj))returns the class's dictionary, including methods and class attributes.hasattr,getattr,setattr, anddelattrread and change attributes by name. They follow the same lookup rules as dot syntax.
class Point:
dimensions = 2
def __init__(self, x, y):
self.x = x
self.y = y
p = Point(1, 2)
print(vars(p)) # {'x': 1, 'y': 2}
print("dimensions" in vars(p)) # False
print(getattr(p, "dimensions")) # 2
print(getattr(p, "z", None)) # None
setattr(p, "x", 10)
print(p.x) # 10Instances normally allow new attributes at any time, so a typo like p.xx = 5 quietly creates a new attribute. A later chapter on __slots__ shows how to restrict that and to reduce per-instance memory.
Common mistakes
- Shared mutable defaults. A list or dict in the class body is shared. Move it into
__init__. - Counters that never change.
self.count += 1shadows the class attribute instead of updating it. Write through the class. - Assuming a class change reaches every instance. Instances that shadowed the name keep their own value.
- Overwriting a method by accident. Assigning
self.name = ...wherenameis also a method name replaces the method on that instance. - Mutable default arguments. The related bug
def __init__(self, items=[])has the same cause, one shared object. UseNoneas the default and create the list inside the function.
Exercise
This class is meant to give each Student its own list of grades, and to count how many students exist. Find the two bugs and fix them. class Student: grades = [] total = 0 def _init(self, name): self.name = name self.total += 1 def addgrade(self, g): self.grades.append(g)
Show answer
Bug 1: grades is a mutable class attribute, so all students share one list. Create it in _init with self.grades = []. Bug 2: self.total += 1 reads the class value and writes an instance attribute, so Student.total stays 0. Write through the class with Student.total += 1, or type(self).total += 1. class Student: total = 0 def init(self, name): self.name = name self.grades = [] type(self).total += 1 def addgrade(self, g): self.grades.append(g)
Exercise
After this code runs, what do the last two print calls show, and why? class Config: level = 1 a, b = Config(), Config() a.level = 5 Config.level = 9 print(a.level) print(b.level)
Show answer
They print 5 and 9. The assignment a.level = 5 created an instance attribute that shadows the class attribute for a. Config.level = 9 changed the class attribute, which b still reads because it never shadowed it.