Python Class Variables
Table of Contents + β
In the last lesson you learned about Instance Variables, the data that belongs to each object on its own. Two objects, two separate copies. That is what you want most of the time. But sometimes you need the opposite. You want one value that every object shares. That is what a class variable is for.
π€ Why Class Variables?
Say you are building a game. You want to know how many Player objects have been created so far. With instance variables you cannot do this cleanly. Each player only knows about itself. None of them knows the total.
So you need one number that lives with the class, not with any single object. Every player adds to it. And every player can read the same value. A class variable gives you exactly that. One shared piece of data that all objects look at together.
π§© What Is a Class Variable?
A class variable is a value that belongs to the class itself. It is shared by every object made from that class.
Think of a classroom. Each student has their own name and their own marks. That is personal. That is instance data. But the room number is the same for everyone in that class. You do not give each student their own copy of the room number. It belongs to the class as a whole. A class variable is that room number.
Here is the key difference in one line:
- An instance variable is defined inside
__init__usingself. Each object gets its own copy. - A class variable is defined in the class body, outside any method. All objects share the one copy.
π οΈ The Syntax
You write a class variable right inside the class body, before __init__, like a normal assignment.
This small class has one class variable called school.
class Student: school = "Greenwood High" # class variable, shared by all students
def __init__(self, name): self.name = name # instance variable, personal to each studentLetβs read that code top to bottom.
school = "Greenwood High"sits in the class body, not inside any method. So it is a class variable.self.name = namesits inside__init__and usesself. So it is an instance variable.
The why is simple. Every student goes to the same school. So it makes sense to store that once on the class. But every student has their own name. So that has to live on each object.
π― A Simple Example
Letβs create two students and read both kinds of variable.
This code makes two Student objects. It prints their personal name and their shared school.
class Student: school = "Greenwood High"
def __init__(self, name): self.name = name
riya = Student("Riya")arjun = Student("Arjun")
print(riya.name, "goes to", riya.school)print(arjun.name, "goes to", arjun.school)When you run it, you get this.
Output
Riya goes to Greenwood HighArjun goes to Greenwood HighSee what happened? riya and arjun have different names. That is because name is personal. But they both report the same school. That is because school is shared. We only wrote that school value once. And both objects can read it.
π’ A Real Example: A Shared Counter
Here is the classic use. We want to count how many Player objects have been created. The counter has to be shared. So it is a perfect shared counter.
This code keeps a running count on the class. It bumps the count up by one every time a new player is made.
class Player: count = 0 # class variable, shared running total
def __init__(self, name): self.name = name Player.count += 1 # add one to the shared total
p1 = Player("Alex")p2 = Player("Riya")p3 = Player("Arjun")
print("Total players created:", Player.count)Running this prints the total.
Output
Total players created: 3Letβs walk through it line by line.
count = 0is the class variable. It starts at zero and is shared by everyPlayer.- Each time
__init__runs,Player.count += 1adds one to that single shared number. - We create three players. So
__init__runs three times. So the count ends at3. Player.countreads the shared value straight from the class.
Notice we wrote Player.count, using the class name, not self.count. That is on purpose. We want to change the one shared counter. We do not want to make a new personal one on each object. More on that in a moment.
βοΈ A Shared Default Value
Class variables are also handy for a default that is the same for everyone until you change it.
This BankAccount class gives every new account the same starting interest rate. The rate is stored once on the class.
class BankAccount: interest_rate = 0.04 # shared default, same for all accounts
def __init__(self, owner, balance): self.owner = owner self.balance = balance
a1 = BankAccount("Alex", 1000)a2 = BankAccount("Riya", 5000)
print(a1.owner, "rate:", a1.interest_rate)print(a2.owner, "rate:", a2.interest_rate)Both accounts read the same rate.
Output
Alex rate: 0.04Riya rate: 0.04The nice thing is you store the rate in one place. If the bank changes it later, you update BankAccount.interest_rate once. Then every account sees the new value. You do not need to touch each account one by one.
π Class Variable vs Instance Variable
Here is the contrast side by side so it sticks. Notice how the one shared copy is the real dividing line.
| Question | Class variable | Instance variable |
|---|---|---|
| Where is it defined? | In the class body, outside any method | Inside __init__, using self |
| Who owns it? | The class itself | Each object on its own |
| How many copies? | One, shared by all objects | One per object |
| Good for? | Shared counts, shared defaults, constants | Personal data like name or balance |
β οΈ Common Mistakes
A few things trip people up with class variables. Watch for these.
Using self when you meant to update the shared value. When you assign with self, Python does not change the class variable. It quietly creates a new instance variable on that one object. The shared value stays untouched.
class Player: count = 0
def __init__(self, name): self.name = name # β Avoid: this makes a personal count on the object, not the shared one # self.count += 1 # β
Good: this updates the one shared counter on the class Player.count += 1Forgetting that all objects see the same value. Changing a class variable through the class changes it for everyone. That is the whole point. But it can surprise you if you expected each object to be separate. If the data should be personal, it belongs in __init__ as an instance variable.
Using a mutable class variable like a list by accident. A shared list is truly shared. So when one object appends to it, every object sees that new item too. If you wanted each object to have its own list, create it in __init__ with self. Do not create it in the class body.
class Team: # β Avoid: one shared list for every team, often not what you want members = []
# β
Good: give each team its own listclass Team: def __init__(self): self.members = []β Best Practices
A few simple habits keep class variables clean and predictable. The word to remember here is shared.
- Use a class variable only when the value really is shared by all objects, like a count, a default, or a constant.
- Update a shared value through the class name, like
Player.count, so it is clear you mean the shared one. - Keep personal data such as
nameorbalanceas instance variables inside__init__. - Be careful with mutable class variables like lists or dictionaries, since every object shares the same one. If each object needs its own, create it in
__init__.
π§© What Youβve Learned
A quick recap of the ideas from this lesson.
- β
A class variable is defined in the class body, outside
__init__, and is shared by every object of the class. - β
An instance variable lives inside
__init__withselfand gives each object its own copy. - β Class variables are great for shared counters, shared defaults, and constants.
- β
Update a shared value through the class name, like
Player.count, not throughself. - β
Assigning with
selfmakes a new personal variable instead of changing the shared one. - β
A mutable class variable like a list is shared by all objects, so use
selfin__init__when each object needs its own.
Check Your Knowledge
Test what you learned. Pick an answer for each question, then click Check.
- 1
Where is a class variable defined?
Why: A class variable is written directly in the class body, outside __init__ and every other method, so it belongs to the class itself.
- 2
How many copies of a class variable exist when you create five objects?
Why: There is only one copy of a class variable, and every object of the class shares that same single value.
- 3
Inside __init__, which line correctly adds one to a shared counter named count on the class Player?
Why: Player.count += 1 updates the one shared counter on the class, while self.count would create a separate personal variable on the object.
- 4
Why is a shared list defined as a class variable often a problem?
Why: A mutable class variable is shared, so when one object appends to the list every object sees that change too.
π Whatβs Next?
You now know how to store data that is shared across every object. Next we will look at how objects actually do things. These are the functions that live inside a class.