
Python
Class variables are attributes that are shared by all instances of a class. While instance variables are unique to each object, class variables have the same value across all objects. Class variables are useful for storing data that applies to the entire class.
Class variables are defined directly in the class body, not in methods. They are accessed through the class name or through instances using `ClassName.variable` or `self.variable`. All instances share the same class variableβchanging it in one place affects it for all objects.
class Car:
wheels = 4 # Class variable - shared by all cars
def __init__(self, brand, color):
self.brand = brand # Instance variable
self.color = color # Instance variable
# All cars share the same wheels value
car1 = Car("Tesla", "red")
car2 = Car("Toyota", "blue")
print(Car.wheels) # Output: 4
print(car1.wheels) # Output: 4
print(car2.wheels) # Output: 4Instance variables are unique to each object, while class variables are shared. Instance variables are defined using `self.variable` in methods. Class variables are defined in the class body without `self.`. This distinction is important for understanding what data belongs to which scope.
class Student:
school = "Central High" # Class variable - shared
student_count = 0 # Class variable - shared
def __init__(self, name, grade):
self.name = name # Instance variable - unique
self.grade = grade # Instance variable - unique
Student.student_count += 1
def introduce(self):
return f"{self.name} from {Student.school}, Grade: {self.grade}"
# Create students
s1 = Student("Alice", "10th")
s2 = Student("Bob", "10th")
s3 = Student("Charlie", "11th")
print(s1.introduce())
# Output: Alice from Central High, Grade: 10th
print(Student.student_count) # Output: 3 - shared across all students
print(s1.student_count) # Output: 3 - access through instanceA common use of class variables is tracking information about all instances. You can count how many objects have been created or track totals across all instances.
class BankAccount:
total_accounts = 0
total_deposits = 0
def __init__(self, owner, balance):
self.owner = owner
self.balance = balance
BankAccount.total_accounts += 1
BankAccount.total_deposits += balance
def deposit(self, amount):
self.balance += amount
BankAccount.total_deposits += amount
return f"Deposited ${amount}"
@staticmethod
def get_bank_stats():
return f"Total accounts: {BankAccount.total_accounts}, Total deposits: ${BankAccount.total_deposits}"
# Create accounts
a1 = BankAccount("Alice", 1000)
a2 = BankAccount("Bob", 500)
a3 = BankAccount("Charlie", 1500)
a1.deposit(200)
a2.deposit(300)
print(BankAccount.get_bank_stats())
# Output: Total accounts: 3, Total deposits: $3500Class variables can be modified through the class or through instances. However, reassigning to `self.variable` creates an instance variable that shadows the class variable. Use `ClassName.variable` to modify the true class variable.
class Game:
level = 1 # Class variable
score = 0 # Class variable
def __init__(self, player_name):
self.player_name = player_name
def advance_level(self):
Game.level += 1 # Modify class variable
def add_score(self, points):
Game.score += points # Modify class variable
def get_status(self):
return f"{self.player_name} - Level {Game.level}, Total Score: {Game.score}"
# Create players
player1 = Game("Alice")
player2 = Game("Bob")
player1.add_score(100)
print(player1.get_status()) # Alice - Level 1, Total Score: 100
player2.add_score(150)
print(player2.get_status()) # Bob - Level 1, Total Score: 250
player1.advance_level()
print(f"Current level: {Game.level}") # Output: 2 - shared by allClass variables are excellent for storing configuration values that apply to all instances of a class. This allows you to change settings for the entire class without modifying individual objects.
class DatabaseConnection:
host = "localhost"
port = 5432
timeout = 30
max_retries = 3
def __init__(self, user):
self.user = user
self.connected = False
def connect(self):
connection_string = f"Connecting to {DatabaseConnection.host}:{DatabaseConnection.port} as {self.user}"
self.connected = True
return connection_string
@staticmethod
def change_host(new_host):
DatabaseConnection.host = new_host
# Create connections
db1 = DatabaseConnection("admin")
db2 = DatabaseConnection("user")
print(db1.connect())
# Output: Connecting to localhost:5432 as admin
# Change configuration for all connections
DatabaseConnection.change_host("remote.server.com")
print(db2.connect())
# Output: Connecting to remote.server.com:5432 as userclass Employee:
department = "Engineering"
annual_raise = 0.05
total_employees = 0
payroll = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.total_employees += 1
Employee.payroll += salary
def give_raise(self):
self.salary *= (1 + Employee.annual_raise)
return f"{self.name}'s new salary: ${self.salary:.2f}"
def get_info(self):
return f"{self.name} - ${self.salary:.2f} (in {Employee.department})"
@staticmethod
def department_summary():
return f"Department: {Employee.department}, Employees: {Employee.total_employees}, Total Payroll: ${Employee.payroll:.2f}"
emp1 = Employee("Alice", 80000)
emp2 = Employee("Bob", 75000)
emp3 = Employee("Charlie", 90000)
print(emp1.give_raise())
print(Employee.department_summary())
# Output: Department: Engineering, Employees: 3, Total Payroll: $252500.00class Recipe:
cuisine = "International"
difficulty_level = "Medium"
recipes_created = 0
def __init__(self, name, servings):
self.name = name
self.servings = servings
self.ingredients = []
Recipe.recipes_created += 1
def add_ingredient(self, ingredient, amount):
self.ingredients.append((ingredient, amount))
def scale_recipe(self, new_servings):
factor = new_servings / self.servings
self.servings = new_servings
return f"Scaled to {new_servings} servings (factor: {factor})"
def get_recipe_info(self):
return f"{self.name} ({Recipe.cuisine}) - {self.servings} servings, {len(self.ingredients)} ingredients"
@staticmethod
def get_stats():
return f"Total recipes: {Recipe.recipes_created}"
r1 = Recipe("Pasta", 4)
r1.add_ingredient("pasta", "400g")
r1.add_ingredient("tomatoes", "800g")
r2 = Recipe("Salad", 2)
r2.add_ingredient("lettuce", "200g")
print(r1.scale_recipe(8))
print(Recipe.get_stats())
# Output: Total recipes: 2| Concept | Remember |
|---|---|
| Class Variable | Defined in class body, shared by all instances |
| Instance Variable | Defined using self, unique to each instance |
| Shared Data | All objects access the same class variable value |
| Modification | Use ClassName.variable to modify class variables |
| Access | Can access through class (Car.wheels) or instance (car.wheels) |
| Common Uses | Counting, configuration, constants, totals |
| Shadowing | Assigning to self.variable creates instance variable |
Now let's explore constructors and how they initialize objects with `__init__`.
Next: Constructors & Initialization β
Ready to practice? Try challenges or explore more concepts
Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep β’ Build Real β’ Verify Skills β’ Launch Forward