Python Class Variables: Declaration, Usage, and Practical Examples
Shared state in Python can be helpful or painful depending on how you use it. A class declaration Python pattern looks simple on the surface, but one misplaced assignment can turn a clean design into a hard-to-track bug where every object changes at once.
Quick Answer
Class declaration Python uses attributes defined on the class itself, not on each instance, to store shared values such as defaults, counters, and constants. As of November 2026, the key rule is simple: use class variables for shared class-wide state and instance variables for per-object data, or you will create confusing shared-state bugs.
Definition
Python class variables are attributes defined on a class rather than on individual objects. They are shared by all instances unless an instance creates its own attribute with the same name.
| Concept | Class variables in Python |
|---|---|
| Where defined | Inside the class body, as of November 2026 |
| Shared across instances | Yes, unless shadowed by an instance attribute, as of November 2026 |
| Best use cases | Defaults, counters, constants, registries, as of November 2026 |
| Common risk | Accidental shared mutable state, as of November 2026 |
| Lookup behavior | Instance first, then class, then parent classes, as of November 2026 |
What Python Class Variables Are and Why They Matter
A class variable is an attribute stored on the class object itself, not inside a single instance. That means every object created from the class can read the same value unless one object creates its own attribute with the same name.
This matters because class variables solve real design problems cleanly. They are useful for shared defaults, object counters, feature flags, labels, and configuration values that belong to the type of object rather than to a single object.
The important difference is scope. A class variable is not a global variable; it belongs to the class namespace and participates in inheritance, so subclasses can read it, override it, or shadow it without touching unrelated code.
Shared class-level data is convenient until it becomes invisible shared state. That is when one line of code starts affecting objects that were supposed to stay independent.
That is why Python developers need to treat class variables with discipline. When the data is stable and truly class-wide, the pattern is clean. When the data changes frequently per object, an instance variable is the safer choice.
- Good fit: shared company name, default tax rate, or a class-wide status label
- Good fit: counting how many objects have been created
- Good fit: storing a registry of instances for later lookup
- Bad fit: user-specific preferences, editable lists, or per-object state that changes often
For Python developers working in production code, this distinction affects debugging time, test stability, and class design. It also matters when inheritance enters the picture, because class variables can be inherited in ways that are helpful until they are misunderstood.
How Does Class Declaration Python Work?
Class declaration Python works by defining attributes directly inside the class body, where they become class-level attributes. Python stores them on the class object, and every instance can access them through attribute lookup.
The mechanism is straightforward, but the consequences are important. If an instance has its own attribute with the same name, that instance value wins during lookup. If not, Python falls back to the class value and then to parent classes.
Declare the attribute in the class body
This is the simplest form and the one most readers expect. You define the shared value once, and every object sees it unless overridden.
class Product:
category = "software"
print(Product.category) # software
Compare it to __init__ initialization
__init__ is for object-specific setup, not shared class-wide data. If you assign a value inside __init__ using self, that value belongs to the instance.
class Product:
category = "software"
def __init__(self, name):
self.name = name
Use it for shared defaults and constants
Class variables are a good place for data that describes the class as a whole. A common example is a default discount rate or a company name shared by every object in the class.
class Employee:
company_name = "ITU Online IT Training"
default_tax_rate = 0.22
Set it later only when there is a clear reason
Sometimes a class variable is assigned after the class is defined, but that should be deliberate and readable. In most codebases, defining it in the class body is clearer because the shared intent is visible immediately.
If the value is not meant to change during runtime, keep it in the class body. If the value is dynamic, consider whether it belongs in a configuration object, an instance attribute, or a dedicated constant module instead.
Official Python documentation on class definitions and data model behavior is the best reference for how attributes are stored and resolved. See the Python Data Model and the Python Tutorial: Classes.
Class Variables vs Instance Variables
Instance variables are attributes that belong to one object and can differ from one instance to another. Class variables belong to the class itself and are shared by all instances unless shadowed.
The cleanest way to think about the difference is this: class variables describe the group, while instance variables describe the individual. If the value should change independently for each object, it belongs on the instance.
| Class variable | Shared by all objects created from the class |
|---|---|
| Instance variable | Unique to one object and stored on that object |
See how shadowing works
Python first checks the instance, then the class. If an object creates an attribute with the same name as the class variable, the instance value shadows the class value for that object only.
class Team:
name = "Engineering"
a = Team()
b = Team()
a.name = "Security"
print(a.name) # Security
print(b.name) # Engineering
print(Team.name) # Engineering
This behavior is where many bugs start. Developers assume they changed the class variable, but they actually created a new instance attribute.
Use a simple decision rule
- Use a class variable when the value describes the class as a whole
- Use an instance variable when the value changes per object
- Use an instance variable when each object should be safe to mutate independently
- Use a class variable for stable defaults or shared metadata
Python’s object model documentation explains why this distinction matters in real code. The behavior is not random; it follows a predictable resolution order described in the official attribute access rules.
How Attribute Lookup Works in Python
Attribute lookup is the process Python uses to find the value of an attribute when you access it on an object. The order matters: Python checks the instance first, then the class, then parent classes through inheritance.
That means the same attribute name can produce different values depending on where it was defined. If you understand lookup order, strange results often become obvious instead of mysterious.
- Check the instance for an attribute with that name.
- Check the class if the instance does not have it.
- Check parent classes if the class does not define it directly.
- Return the first match found in that chain.
Why this matters during debugging
Unexpected output is often not a broken program. It is usually an attribute lookup issue, where the code is reading an instance value instead of the class variable, or inheriting a value from a parent class that the developer forgot about.
This is especially important in larger codebases with multiple layers of inheritance. A subclass can appear to “have” a value without defining it directly, which is perfectly legal but easy to misread during debugging.
Inheritance changes the picture
If a subclass does not redefine a class variable, it inherits the parent’s version. If the subclass assigns the same name, it creates or shadows a class attribute on the subclass instead of changing the parent.
class Vehicle:
wheels = 4
class Bike(Vehicle):
wheels = 2
print(Vehicle.wheels) # 4
print(Bike.wheels) # 2
For a deeper explanation of lookup and resolution behavior, Python’s official documentation on classes and inheritance is the most reliable reference.
Using Class Variables Correctly with __init__
__init__ should usually set instance variables, not class variables. That is because its job is to initialize one object, while class variables are shared across the class.
A safe pattern is to read a class variable inside __init__ and copy it into an instance attribute only when each object needs its own version. This avoids accidental shared mutation while still giving you a sensible default.
Copy shared defaults into instance state when needed
class User:
default_role = "viewer"
def __init__(self, name, role=None):
self.name = name
self.role = role if role is not None else User.default_role
Here, the class variable provides a shared default, but each object gets its own role value. That is a clean design because changing one user does not affect the others.
Avoid assigning to self when you mean the class
If you write self.counter += 1, you may create an instance attribute instead of updating the class-level counter. If the intent is shared state, use the class name explicitly.
class Session:
count = 0
def __init__(self):
Session.count += 1
This is one of the most common mistakes in class declaration Python examples. The code looks right at a glance, but the assignment target controls whether the change affects one object or all objects.
Pro Tip
If a value should be identical for every object, store it on the class and access it through the class name. If each object may need its own version, store it on the instance and keep the shared default only as a fallback.
Python’s official guidance on class design and the data model reinforces this distinction. The Python Data Model explains how objects store and expose attributes.
Accessing Class Variables the Right Way
You can access a class variable through the class name or through an instance, but the class name is usually clearer. When you use the class name, readers immediately know the value belongs to the class and not to one object.
That clarity pays off during maintenance. In a team setting, explicit access reduces ambiguity and makes code review easier because the intent is obvious.
Prefer class-name access for shared values
class Invoice:
tax_rate = 0.10
print(Invoice.tax_rate)
That style is especially useful for constants, counters, and shared configuration. It keeps the code honest about ownership.
Instance access is okay for reading, not for clarity
Reading a class variable through an instance works, but it can hide the fact that the value is shared. That is acceptable for quick inspection or lightweight code, but it is usually not the best style for long-term maintainability.
When a team uses one pattern consistently, the codebase becomes easier to scan. The problem is rarely the access itself; the problem is inconsistency.
- Use the class name when the value is shared by design
- Use the instance only when you are intentionally reading inherited or shared behavior
- Do not mix styles randomly in the same codebase
The official Python classes documentation and data model are the best references for this pattern. See Python classes for the language-level behavior.
Common Use Cases for Class Variables
Class variables work best when the value belongs to the class as a concept rather than to an individual object. That usually means shared defaults, counters, registries, or metadata that applies to all instances.
A good class variable makes intent obvious. A bad one creates hidden coupling between objects that should not influence one another.
Shared constants and defaults
A company name, default region, or standard rate often belongs on the class because every object starts from the same baseline.
class Account:
currency = "USD"
service_fee = 5.00
Object counters
Class variables are a natural way to count how many objects have been created. This is useful for monitoring, debugging, or lightweight metrics inside an application.
class Widget:
total_created = 0
def __init__(self):
Widget.total_created += 1
Registries and lookup lists
A class-level registry can collect every instance so the program can find them later. This pattern is common in plugin systems, caches, and object catalogs.
class Plugin:
registry = []
def __init__(self, name):
self.name = name
Plugin.registry.append(self)
Shared configuration flags
Feature flags or behavior toggles sometimes belong on the class when they apply to every instance. If the flag is changed, all instances see the new value unless they override it locally.
These examples are simple, but the design principle is important: use class variables for values that describe the class itself. If the value is really part of one object’s identity, move it to the instance.
For broader context on object design and configuration patterns, Python’s own documentation remains the authoritative source. In production environments, that principle is reinforced by how the language is specified in the official object model.
Why Are Mutable Class Variables Risky?
Mutable class variables are risky because a list, dictionary, or set stored on the class is shared by every instance. If one object changes it, every other object sees the change too.
This is one of the easiest ways to create hidden bugs in Python. The code may work in a single test and fail later when multiple objects are active at the same time.
The classic shared list bug
class OrderBatch:
items = []
def add_item(self, item):
self.items.append(item)
That code looks harmless, but items is shared by every instance. If two batches exist, both will show the same list, which is usually not what you want.
Safer patterns
- Use instance variables for object-specific collections
- Copy a class default before mutating it
- Use tuples or strings for shared data that should not change
- Document the shared collection clearly if a registry is intentional
class OrderBatch:
default_tags = ("new", "pending")
def __init__(self):
self.tags = list(self.default_tags)
That version gives each object its own list while keeping the default values centralized on the class.
Warning
If a class variable is a list, dictionary, or set, assume it is shared state and verify whether that is truly what you want before you mutate it.
For language-level guidance on safe Python behavior, the official Python documentation is the best source. For defensive coding patterns around shared mutable state, the same object model rules apply regardless of project size.
How Inheritance Changes Class Variables
Inheritance is the mechanism that lets one class reuse behavior and data from another class. Class variables participate in inheritance, which means subclasses can read them unless they override the value.
This behavior is useful, but it also creates subtle differences between reading, overriding, and modifying. A subclass that assigns a value with the same name does not change the parent’s class variable; it creates its own class-level attribute.
Read from the parent without redefining
class Animal:
kingdom = "Animalia"
class Cat(Animal):
pass
print(Cat.kingdom) # Animalia
Override the value in the child class
class Animal:
legs = 0
class Spider(Animal):
legs = 8
The child class now has its own class variable. The parent remains unchanged.
Understand parent change versus child shadowing
If you update the parent class variable, subclasses that have not overridden it will see the new value. If a subclass has already defined its own attribute with the same name, it will keep using its own version.
This is why inheritance-based designs should be read carefully. Shared state can flow down a hierarchy, but not always the way a new developer expects.
Python’s inheritance behavior is documented in the official classes and inheritance guide, which is the right reference when you need exact behavior.
Practical Examples of Python Class Variables
The best way to understand class variables is to see them in code. These examples show the most common real-world patterns: shared defaults, counters, registries, and subclass overrides.
Shared company name
class Employee:
company_name = "ITU Online IT Training"
def __init__(self, name):
self.name = name
e1 = Employee("Ava")
e2 = Employee("Noah")
print(e1.company_name)
print(e2.company_name)
print(Employee.company_name)
All three accesses return the same shared class value. That is exactly what you want for a company name.
Counting created objects
class Session:
total_sessions = 0
def __init__(self):
Session.total_sessions += 1
s1 = Session()
s2 = Session()
print(Session.total_sessions) # 2
This pattern is useful when you need lightweight tracking across all instances. It is clean because the counter belongs to the class as a whole.
Building a shared registry
class Service:
registry = []
def __init__(self, name):
self.name = name
Service.registry.append(self)
Now every new object is available in one shared collection. That can be useful for discovery, reporting, or lifecycle management.
Subclass override example
class Report:
format = "PDF"
class CsvReport(Report):
format = "CSV"
print(Report.format) # PDF
print(CsvReport.format) # CSV
This shows how a subclass can define a different class-level value while still inheriting the parent structure.
The value of class variables is not in the syntax. It is in the design choice: shared data becomes easier to manage when the code says so explicitly.
For formal background, Python’s class model and inheritance behavior are documented by the Python Software Foundation at docs.python.org.
What Are the Most Common Mistakes to Avoid?
The most common class variable mistakes come from assuming a value is private to one object when it is actually shared. That misunderstanding creates side effects that often show up far from the code that caused them.
Another common error is using self.variable when the real goal was to change the class variable. That assignment can silently create a new instance attribute and leave the class unchanged.
- Assuming class variables are per-object when they are shared.
- Mutating a shared list or dictionary and accidentally affecting every instance.
- Using self when the class name is required for shared state updates.
- Expecting child-class changes to update the parent in the same way.
- Putting too much on the class when the design actually needs instance data.
These mistakes are especially painful in tests. One test mutates shared state, the next test inherits the modified value, and the failure seems unrelated to the original change.
Good debugging habits help here. If output looks wrong, inspect whether the value lives on the instance or the class, then verify whether inheritance is contributing a hidden value.
What Are the Best Practices for Safe and Maintainable Class Variable Use?
Use class variables intentionally. The best designs are the ones where another developer can tell, at a glance, whether a value is shared or specific to one object.
That means class variables should be stable, well-named, and limited to data that truly belongs to the class.
Follow these practical rules
- Keep class variables for shared, stable data
- Prefer immutable values when possible
- Use explicit class-name access for clarity
- Document mutable shared collections if you must use them
- Review shared state in code review before it reaches production
Make defaults obvious
If a class variable is acting as a default, make that obvious in the name or structure. A name like default_status is easier to understand than a vague status that silently applies to every instance.
Separate shared data from changing data
Shared data should usually be static or slowly changing. If each object modifies the value often, the class is probably the wrong place for it.
For teams building maintainable Python systems, these practices reduce debugging time and make inheritance behavior predictable. The official Python docs remain the reference point, but the discipline comes from the code review process.
When Should You Use Class Variables and When Should You Avoid Them?
Use class variables when the value describes the class, not the object. Avoid them when each object needs its own state that changes independently.
That decision sounds simple, but it becomes clearer with examples. A default company label belongs on the class. A customer’s email address does not.
Use class variables for these cases
- Shared defaults that every instance can read
- Constants that should remain the same for the class
- Counters that track all instances together
- Metadata that describes the class as a whole
- Registries where every instance should be discoverable
Avoid class variables for these cases
- Per-user settings that must not leak between objects
- Frequently mutated collections that should stay isolated
- Object identity fields such as IDs or personal details
- Data that differs per request in web or service code
In larger systems, the right choice is often about maintainability more than syntax. The simpler the ownership model, the easier the code is to reason about later.
If you need a practical test, ask one question: Should every object see the same value, or should each object manage its own copy? That answer usually tells you whether to use a class variable or an instance variable.
Key Takeaway
Class variables are shared by the class and inherited by subclasses unless overridden.
Instance variables belong to one object and are the right choice for independent state.
Python attribute lookup checks the instance first, then the class, then parent classes.
Mutable class variables can create hidden bugs because every instance shares the same underlying object.
Use the class name for shared state and use self for per-object state.
Conclusion
Python class variables are powerful when you use them for the right job. They are ideal for shared defaults, counters, constants, registries, and class-wide metadata, but they become dangerous when you confuse shared state with per-object state.
The central lesson is simple: class variables belong to the class, instance variables belong to the object. Once you understand attribute lookup and inheritance, the confusing edge cases become much easier to predict.
Before you add a class variable, ask whether the value should be shared by all objects or isolated to one object. That one decision prevents most of the bugs tied to class declaration Python patterns.
If you want to go deeper, review Python’s official documentation on classes, inheritance, and the data model, then apply those rules in a small test class before using them in production code. That habit pays off fast.
Python is a trademark of the Python Software Foundation.

