Python Class vs Instance Attributes
@Chris Ried on Splash

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

  1. Use class attributes for constants and shared defaults
  2. Define instance attributes in init
  3. Be explicit about your intentions

Don't

  1. Use mutable class attributes (lists, dicts) without careful consideration
  2. Add attributes dynamically unless necessary
  3. Assume all attributes work the same way




To view or add a comment, sign in

More articles by Benjamin Kettey-Tagoe

  • How Do SQL Database Engines Work?

    Ever wondered how your favorite apps store and retrieve millions of pieces of information in seconds? Let me explain…

  • Python: Mutable & Unmutable

    During a recent Python project, I dove into one of the most powerful yet often misunderstood aspects of Python: how it…

Explore content categories