Distinguish Class and Instance Attributes
Core idea
A class attribute belongs to the class. For ordinary data attributes, an instance can read a class attribute when it has no attribute of the same name. Assigning to the instance normally creates its own binding instead. Mutable objects stored on the class can be shared by every instance that reads them.
class Ticket: zone = "north"
a = Ticket()b = Ticket()print(a.zone, b.zone)Both lookups find the class attribute.
Shadow a shared value
class Ticket: zone = "north"
a = Ticket()a.zone = "south"Ticket.zone = "west"print(a.zone, Ticket().zone)a has its own zone; a new instance reads the updated class value.
Observe shared mutable data
class Queue: items = []
a = Queue()b = Queue()a.items.append("box")print(b.items)Both lookups reach the same list. Appending mutates that list rather than creating an instance attribute.
Common mistake
Keep shared mutable class attributes only when sharing is intentional. Create separate lists on each instance for independent state. Properties have additional lookup rules, introduced later in this chapter.
Practice
Replace the shared Queue list with two lists assigned separately to a.items and b.items. Append to one and inspect the other.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Distinguish shared and independent attributes
Check your understanding of class attributes.
What is printed?
class Tag: zone = "west"a = Tag()a.zone = "east"print(a.zone, Tag().zone)What is printed?
class Tag: n = 1a = Tag()Tag.n = 3print(a.n)What is printed?
class Tag: items = []a = Tag()a.items.append(7)print(Tag().items)How can each instance have its own list?