Python Class vs Instance Attributes
Ever wondered why changing a property in one object affects ALL objects, while others stay private? Let's demystify this fundamental Python concept!
The Core Problem
Many developers get confused when their code behaves unexpectedly. Understanding the difference between class and instance attributes is crucial for writing clean, predictable Python code.
Class Attributes
Let's define the class attributes at the class level and shared by ALL instances
class Dog:
species = "Canis lupus" # Class attribute
def init(self, name):
self.name = name # Instance attribute
fido = Dog("Fido")
buddy = Dog("Buddy")
print(fido.species, buddy.species) # Canis lupus
NB: Key insight: Change it once, affects everywhere
Instance Attributes
Instance attributes belong to individual objects
class Dog:
def init(self, name):
self.name = name # Unique to each instance
fido = Dog("Fido")
buddy = Dog("Buddy")
print(fido.name, buddy.name) # Fido Buddy
NB: Each dog keeps its own name
The Mutable Trap
class Team:
members = [] Dangerous!
team_a = Team()
team_b = Team()
team_a.members.append("Alice")
print(team_b.members) # ['Alice'] Surprise!
Solution: Always initialize mutable attributes in init:
class Team:
def init(self):
self.members = [] # Safe!
Best Practices
Do
Don't