Class variables
- Python course
- Intermediate
- Lesson 27/116
- 4 min
Learn to share class-level variables.
Class variable
A class variable is a variable defined directly in the class body. All instances share it. It is accessed as Class.name or instance.name.
Example: class Counter:\n count = 0. Counter.count gives the same value for all instances. An instance variable (self.x) is per instance; a class variable is shared by all. This distinction matters for sharing common state.
Class vs instance variable
A class variable is shared across all instances; an instance variable is per instance. Inside __init__, self.x is an instance variable; in the body, a direct x is a class variable.
Example: class Counter:\n count = 0\n def __init__(self):\n Counter.count += 1. Each new instance increments count. After c1 = Counter(); c2 = Counter(), Counter.count is 2. This is useful for an instance counter.
Practice Add a class variable to Counter
Define the Counter class. Add the class variable count = 0 in the body. Add the method def __init__(self): and in the body write Counter.count += 1. Then create two instances with c1 = Counter() and c2 = Counter() and write print(Counter.count).
Starter code
# Define the Counter classSample solution
# Define the Counter class
class Counter:
count = 0
def __init__(self):
Counter.count += 1
c1 = Counter()
c2 = Counter()
print(Counter.count)Expected output
2
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 How is a class variable accessed?
- Only via an instance
- Only via the class
- Only inside a method
- Both via instance and class Correct answer
Explanation: A class variable is accessed both via the class and an instance.
2 Complete the class variable
class Counter:
____ = 0
class Counter:
count = 0
Explanation: count is written directly in the body; it is not an instance variable.
3 Match the variable types
| Term | Meaning |
|---|---|
count = 0 |
Class variable |
self.x = 1 |
Instance variable |
Counter.count += 1 |
Update class state |