How to Create Class Variable in Python: Simple Guide
In Python, create a class variable by defining it directly inside the class but outside any methods using
variable_name = value. This variable is shared by all instances of the class and accessed via ClassName.variable_name or self.variable_name inside methods.Syntax
Define a class variable inside the class but outside any method. It belongs to the class itself, not to any single object.
- ClassName: The name of your class.
- variable_name: The name of the class variable.
- value: The value assigned to the class variable.
python
class ClassName:
variable_name = valueExample
This example shows a class variable count that keeps track of how many objects have been created from the class.
python
class Dog: count = 0 # class variable shared by all dogs def __init__(self, name): self.name = name # instance variable unique to each dog Dog.count += 1 # Create dogs dog1 = Dog('Buddy') dog2 = Dog('Lucy') print(Dog.count) # Access class variable via class print(dog1.count) # Access class variable via instance print(dog2.count) # Same value shared by all instances
Output
2
2
2
Common Pitfalls
One common mistake is trying to create a class variable inside the __init__ method using self.variable_name. This creates an instance variable instead, which is unique to each object and does not share the value across instances.
Another pitfall is modifying a class variable via an instance, which creates a new instance variable and leaves the class variable unchanged.
python
class Cat: count = 0 # class variable def __init__(self, name): self.name = name # Wrong: this creates instance variable, not changes class variable self.count = Cat.count + 1 cat1 = Cat('Milo') cat2 = Cat('Luna') print(Cat.count) # Still 0, class variable unchanged print(cat1.count) # 1, instance variable print(cat2.count) # 1, instance variable # Correct way: class CatCorrect: count = 0 def __init__(self, name): self.name = name CatCorrect.count += 1 cat3 = CatCorrect('Simba') cat4 = CatCorrect('Nala') print(CatCorrect.count) # 2, class variable updated correctly
Output
0
1
1
2
Quick Reference
Class Variable Cheat Sheet:
- Define inside class, outside methods:
variable = value - Access via
ClassName.variableorself.variable - Shared by all instances
- Modify using
ClassName.variable = new_valueto affect all instances - Modifying via instance creates a new instance variable (avoid this)
Key Takeaways
Class variables are defined inside the class but outside any method using simple assignment.
They are shared by all instances of the class and accessed via the class name or instances.
Avoid creating class variables inside __init__ with self; that makes instance variables instead.
Modify class variables using the class name to update the shared value for all objects.
Accessing a class variable via an instance is allowed but modifying it via instance creates a new instance variable.