Skip to content

Instantly share code, notes, and snippets.

@gengwg
Created July 15, 2025 17:30
Show Gist options
  • Save gengwg/9b6afd1b7bd543eab192279da6b22749 to your computer and use it in GitHub Desktop.
Save gengwg/9b6afd1b7bd543eab192279da6b22749 to your computer and use it in GitHub Desktop.
p.bar() # Calls RealObject's bar method

Class Attributes vs Instance Attributes in Python

Class Attributes

  • Defined directly inside the class definition
  • Shared by all instances of the class
  • The same value is accessible from all instances
  • Changing it affects all instances

Instance Attributes

  • Defined inside methods (typically __init__)
  • Unique to each instance
  • Each instance can have different values
  • Changing one instance doesn't affect others
class Dog:
    # Class attribute
    species = "Canis familiaris"
    count = 0  # Tracks how many dogs we've created
    
    def __init__(self, name, age):
        # Instance attributes
        self.name = name
        self.age = age
        Dog.count += 1  # Increment the class attribute
    
    def description(self):
        return f"{self.name} is {self.age} years old"
    
    def speak(self, sound):
        return f"{self.name} says {sound}"

# Create instances
buddy = Dog("Buddy", 9)
miles = Dog("Miles", 4)

# Access class attribute (same for all instances)
print(buddy.species)  # Canis familiaris
print(miles.species)   # Canis familiaris
print(Dog.species)     # Canis familiaris

# Access instance attributes (unique to each instance)
print(buddy.name)      # Buddy
print(miles.name)      # Miles

# Modify instance attribute (only affects one instance)
buddy.age = 10
print(buddy.age)       # 10
print(miles.age)       # 4 (unchanged)

# Modify class attribute (affects all instances)
Dog.species = "Canis lupus"
print(buddy.species)   # Canis lupus
print(miles.species)   # Canis lupus

# Class attribute tracking instances
print(f"Total dogs created: {Dog.count}")  # 2

# You can also add instance attributes dynamically
buddy.breed = "Golden Retriever"
print(buddy.breed)     # Golden Retriever
# print(miles.breed)   # AttributeError (only buddy has this)

Key Differences:

  1. Scope: Class attributes belong to the class, instance attributes belong to objects
  2. Memory: Class attributes are stored once per class, instance attributes per object
  3. Access: Class attributes can be accessed through class or instance, instance only through instance
  4. Modification: Changing class attribute affects all instances, instance only affects one

Class attributes are often used for:

  • Constants/defaults shared by all instances
  • Tracking class-wide data (like counting instances)
  • Configuration values that should be consistent across instances
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment