🧱 Python Object-Oriented Programming (OOP)
Estimated reading: 3 minutes 22 views

🏷️ Python Class Attributes – Shared State Across Instances

🧲 Introduction – Why Use Class Attributes?

In Python OOP, class attributes are attributes that are shared across all instances of a class. Unlike instance attributes (defined with self), class attributes:

  • Belong to the class itself, not to individual objects
  • Are stored only once in memory
  • Can be accessed or modified using either the class or any of its objects

They are useful when you want shared data or constants across all objects.

🎯 In this guide, you’ll learn:

  • What class attributes are
  • How they differ from instance attributes
  • How to access and modify them
  • Use cases and best practices
  • Real-world examples and gotchas

βœ… What Are Class Attributes?

A class attribute is defined inside the class but outside all methods.

class Car:
    wheels = 4  # class attribute

    def __init__(self, brand):
        self.brand = brand  # instance attribute

πŸ” Accessing Class Attributes

πŸ”Ή Using the class name:

print(Car.wheels)  # 4

πŸ”Ή Using an instance:

c1 = Car("Tesla")
print(c1.wheels)  # 4

πŸ’‘ Even though you’re using an object, it refers to the class attribute if no instance attribute of the same name exists.


πŸ”„ Modifying Class Attributes

βœ… Change it for all instances:

Car.wheels = 6
print(c1.wheels)  # 6

⚠️ Overriding with an instance attribute:

c1.wheels = 8
print(c1.wheels)      # 8
print(Car.wheels)     # 6 (unchanged)

πŸ’‘ When you assign c1.wheels = 8, it creates an instance attribute that shadows the class attribute.


πŸ“‹ Class vs Instance Attributes

FeatureClass AttributeInstance Attribute
Defined where?Outside methodsInside __init__()
Belongs toClassObject
MemorySharedUnique per object
Accessed byClassName.attr or obj.attrself.attr
Use caseConstants, defaultsUnique object data

πŸ§ͺ Real-World Example – Counting Instances

class User:
    count = 0  # class attribute

    def __init__(self, name):
        self.name = name
        User.count += 1
u1 = User("Alice")
u2 = User("Bob")
print(User.count)  # 2

πŸ’‘ The count attribute is shared and updated across all objects.


🧱 Example – Shared Configuration

class Config:
    debug = True
    version = "1.0.0"
print(Config.debug)  # True
Config.debug = False
print(Config.debug)  # False

⚠️ Common Mistakes

❌ Mistakeβœ… Fix
Modifying class attribute via objectAlways modify using class name
Assuming class attribute is unique per objectUse instance attributes for object-specific data
Using mutable class attributes (e.g., lists) without careCopy them in __init__ for safety

πŸ“˜ Best Practices

βœ… Do This❌ Avoid This
Use class attributes for constants or countersStore per-object data in class attributes
Access them via ClassName.attr for clarityRely on obj.attr when unsure
Document with commentsLeave default values unexplained
Be cautious with mutable class attributesUse copies inside __init__ if needed

πŸ“Œ Summary – Recap & Next Steps

Python class attributes provide a powerful way to share common data across all instances of a class. Use them to define default values, constants, or track instance counts.

πŸ” Key Takeaways:

  • βœ… Class attributes are shared by all instances
  • βœ… Defined at the class level, outside methods
  • βœ… Modifying via instance creates a new instance variable
  • βœ… Useful for defaults, counters, and configuration flags

βš™οΈ Real-World Relevance:
Used in web configurations, singleton designs, ORMs, data models, and analytics counters.


❓ FAQ – Python Class Attributes

❓ Are class attributes shared across all objects?

βœ… Yes. They are stored once and shared unless overridden in an instance.

❓ Can class attributes be changed?

βœ… Yes, using ClassName.attribute = value. This change will reflect in all objects (unless overridden).

❓ Can class attributes be accessed using self?

βœ… Yes, but it’s better to use ClassName.attr for clarity when modifying them.

❓ What happens if I modify a class attribute using an instance?

❌ It creates an instance attribute, not modifying the class one. Always update using the class name.

❓ Should I store mutable defaults in class attributes?

⚠️ Be careful. Shared mutable objects like lists/dicts can cause unexpected behavior across instances. Prefer creating a fresh copy in __init__().


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

Python Class Attributes

Or Copy Link

CONTENTS
Scroll to Top