Python ClassVar: Class Variables Explained
python classvar: Understand Python class variables, how they differ from instance variables, and when to use them without introducing shared-state bugs.

In Python, a class variable is a variable defined directly inside a class body, shared by all instances of that class. Unlike instance variables, which are assigned to self, class variables are accessed via the class itself or through an instance. Understanding how python classvar behaves is essential for writing predictable object-oriented code, especially when you need shared configuration, counters, or default values.
Class Variables vs Instance Variables
A class variable is declared inside the class but outside any method. An instance variable is typically assigned inside __init__ using self. The key difference is scope: class variables belong to the class, while instance variables belong to each object.
class Employee:
company = "Acme" # class variable
def __init__(self, name):
self.name = name # instance variable
e1 = Employee("Alice")
e2 = Employee("Bob")
print(e1.company) # Acme
print(e2.company) # AcmeHere, company is shared. Both instances see the same value because they look up the attribute on the class when it is not found on the instance.
Accessing Class Variables Through Instances
When you access e1.company, Python first checks the instance's __dict__. If the attribute is not found there, it looks up the class. This lookup order is why class variables are visible from instances. However, if you assign e1.company = "Other", you create an instance variable that shadows the class variable for that instance only.
e1.company = "Other"
print(e1.company) # Other
print(e2.company) # Acme
print(Employee.company) # AcmeThis behavior is a common source of confusion. Assigning to an instance attribute never changes the class variable; it only creates a new attribute on that instance.
Mutable Class Variables and Shared State
A class variable that is mutable—like a list or dictionary—is shared across all instances. This can be useful, but it also introduces risk if any instance mutates it.
class ShoppingCart:
items = [] # shared mutable class variable
def add(self, item):
self.items.append(item)
cart1 = ShoppingCart()
cart2 = ShoppingCart()
cart1.add("apple")
print(cart2.items) # ['apple']Because items is a class variable, both carts share the same list. If you intend each cart to have its own list, this is a bug. The fix is to assign an instance variable in __init__:
class ShoppingCart:
def __init__(self):
self.items = []
def add(self, item):
self.items.append(item)The shared list is a classic Python pitfall. Use class variables for immutable defaults or constants, and use instance variables for per-object state.
Class Variables and Inheritance
Class variables are inherited by subclasses. If a subclass does not define its own version, it sees the parent's value. But if the subclass assigns a new value to the same name, it creates a separate class variable on the subclass.
class Animal:
kind = "unknown"
class Dog(Animal):
pass
class Cat(Animal):
kind = "feline"
print(Dog.kind) # unknown
print(Cat.kind) # feline
print(Animal.kind) # unknownThis behavior allows you to override defaults per subclass without affecting the parent or sibling classes. However, be careful with mutable class variables in inheritance: if a subclass mutates an inherited mutable class variable, the mutation affects the parent and all other subclasses that share it.
Common Mistakes and Pitfalls
One frequent mistake is using a mutable class variable as a default for instance state. Another is expecting that assigning to self.attr will update the class variable. Also, using self.__class__.attr to modify a class variable from an instance can be useful, but it bypasses the normal lookup and can be confusing.
class Counter:
count = 0
def increment(self):
self.__class__.count += 1This increments the class variable correctly. But if you use self.count += 1, Python reads the class variable, adds one, and assigns a new instance variable, leaving the class variable unchanged. This is a subtle but important distinction.
When to Use Class Variables
Class variables are appropriate for constants, shared configuration, or values that should be identical across all instances. They are also useful for tracking class-level state, such as a count of created instances, but only if you manage mutation carefully. For per-instance data, always use instance variables. The choice affects memory usage: class variables exist once, while instance variables are stored per object. For large numbers of objects, storing data on the class can reduce memory, but it also introduces shared-state risks.
Try matching browser tools
All toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesPython iter(): How the Built-in Function Works
Explains Python's iter() built-in: how it creates iterators, the two-argument sentinel form, custom iterator classes, and common edge cases.
Python Pika: Queues, Exchanges, Routing Keys, and Acknowledgements
Learn how to use Python's Pika client with RabbitMQ: declare queues and exchanges, publish with routing keys, consume messages, and handle acknowledgements reliably.
Python Kafka: kafka-python vs Confluent Client
python kafka python vs confluent kafka: Compare kafka-python and Confluent Kafka Python clients: API differences, performance, feature coverage, and when to choose eac...
Python Kafka Offsets, Partitions, and Manual Commits
Learn how Kafka offsets and partitions work and how to manually commit offsets in Python consumers with kafka-python and confluent-kafka. Covers sync vs async commits, rebalances, and seeking.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.