Class Variables in Python
Class variables are variables that are shared among all instances of a class. They are defined within a class but outside any instance…
Class Variables in Python
Photo by Hitesh Choudhary on Unsplash
Class variables are variables that are shared among all instances of a class. They are defined within a class but outside any instance methods and are usually used to store data that should be the same across all instances.
Read for free: https://allwin-raju.medium.com/class-variables-in-python-3c27600928ee?sk=9608a4153e5c3bbd9901103a09976725
Defining Class Variables
Class variables are defined at the class level and can be accessed using either the class name or an instance.
class Car:
# Class variable
wheels = 4
def __init__(self, brand, color):
self.brand = brand # Instance variable
self.color = color # Instance variable
# Accessing class variable
print(Car.wheels) # Output: 4
# Creating instances
car1 = Car("Toyota", "Red")
car2 = Car("Honda", "Blue")
# Accessing class variable via instance
print(car1.wheels) # Output: 4
print(car2.wheels) # Output: 4
Modifying Class Variables
- Modifying at the Class Level
- Affects all instances.
Car.wheels = 6 # Changing the class variable
print(car1.wheels) # Output: 6
print(car2.wheels) # Output: 6
- Modifying at the Instance Level
- Creates an instance-specific variable rather than modifying the class variable.
car1.wheels = 5 # This only changes for car1
print(car1.wheels) # Output: 5
print(car2.wheels) # Output: 6 (unchanged)
Accessing Class Variables
Class variables are usually accessed inside class methods using cls instead of self.
class Animal:
species = "Mammal" # Class variable
def __init__(self, name):
self.name = name # Instance variable
@classmethod
def set_species(cls, new_species):
cls.species = new_species # Modifying class variable
# Accessing and modifying class variable
print(Animal.species) # Output: Mammal
Animal.set_species("Reptile")
print(Animal.species) # Output: Reptile
When to Use Class Variables?
- When the data should be shared across all instances
- When using constants or default values
- When maintaining global counters or tracking objects
메타데이터
- post_id
- 3c27600928ee
- slug
- class-variables-in-python-3c27600928ee
- url
- https://medium.com/@allwin-raju/class-variables-in-python-3c27600928ee
- canonical_url
- https://medium.com/@allwin-raju/class-variables-in-python-3c27600928ee
- author_url
- https://medium.com/@allwin-raju
- status
- ok
- fetched_at
- 2026-08-28 23:52:44