Store Independent Instance Attributes
Core idea
An attribute is a named value accessed with a dot. Ordinary user-defined instances can store attributes such as item.count. Assigning self.count inside a method changes the receiver’s state. Two separately created instances can hold different values.
class Bin: pass
a = Bin()b = Bin()a.count = 4b.count = 9print(a.count, b.count)Each assignment creates an attribute on its own instance.
Update the receiver
class Bin: def add(self, amount): self.count += amount
a = Bin()a.count = 3a.add(2)print(a.count)add reads and reassigns the attribute on a. The starting attribute must exist.
Intentional failure: absent attribute
No count exists on the instance or its class, so lookup fails.
Common mistake
Writing count = amount in a method creates a local name, not an instance attribute. Use self.count for object state. Initialization will be covered shortly.
Practice
Create two bins with different counts; add three to the first only and predict both counts.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Maintain instance state
Check your understanding of instance attributes.
What is printed?
class Jar: passa = Jar()b = Jar()a.n = 2b.n = 5print(a.n, b.n)What is printed?
class Jar: def add(self, n): self.n += na = Jar()a.n = 3a.add(3)print(a.n)Which exception is raised?
class Jar: def set_count(self): count = 4a = Jar()a.set_count()print(a.count)Where should a method store a persistent per-instance count?