How to Access and Update Class Variables in Python
In Python, class variables are shared among all instances of a class. They are defined directly within the class, outside of any instance methods (like __init__
).
This guide explains how to define, access, and update class variables, and highlights the key differences between class variables and instance variables.
Defining and Accessing Class Variables
Class variables are defined directly within the class body:
class Employee():
cls_id = 'employee' # Class variable
def __init__(self, name, salary):
self.name = name # Instance variable
self.salary = salary # Instance variable
cls_id
: This is a class variable. It's associated with theEmployee
class itself, not with any specificEmployee
object.self.name
,self.salary
: These are instance variables. EachEmployee
object will have its own copy of these.
You can access class variables using the class name:
print(Employee.cls_id) # Output: employee
Updating Class Variables
Updating via the Class
The most straightforward way to update a class variable is to access it directly through the class name:
print(Employee.cls_id) # Output: employee
Employee.cls_id = 'new_employee_id' # Update the class variable
print(Employee.cls_id) # Output: new_employee_id
This change will be reflected in all instances of the class (and in the class itself), because they all share the same class variable.
Updating via a Class Method
It's often better practice to update class variables through @classmethod
s. This provides a clear and controlled way to modify class-level state:
class Employee():
cls_id = 'employee'
def __init__(self, name, salary):
self.name = name
self.salary = salary
@classmethod
def set_cls_id(cls, new_cls_id): # Use "cls" by convention
cls.cls_id = new_cls_id # Update via the class reference.
return cls.cls_id
- A class method receives the class itself (conventionally named
cls
) as the first argument. - The
@classmethod
decorator is used to indicate the method defined is a class method. - You can then call this method like this:
Employee.set_cls_id('another_id')
.
Updating via an Instance (and why it's tricky)
You can technically access and even "modify" a class variable through an instance:
tom = Employee('tomnolan', 100)
print(tom.cls_id) # Output: employee (accessing via instance)
tom.cls_id = 'new' # This creates an *instance* variable!
print(tom.cls_id) # Output: new (instance variable)
print(Employee.cls_id) # Output: new_employee_id (class variable unchanged!)
- The line
tom.cls_id = 'new'
created an instance variable, because when using dot notation on an instance, you are always modifying or accessing an instance variable.
To access the class variable from the instance use:
class Employee():
cls_id = 'employee'
def __init__(self, name, salary):
self.name = name
self.salary = salary
tom = Employee('tomnolan', 100)
result = type(tom).cls_id # or tom.__class__.cls_id
print(result) # Output: employee
- This code demonstrates the correct way to access the class variable from an instance, if you really need to.
type(tom)
(ortom.__class__
) gets the class of the instance, and then you accesscls_id
on the class.
Accessing Instance Variables
Instance variables are unique to each object:
class Employee():
cls_id = 'employee' # class variable
def __init__(self, name, salary):
self.name = name # instance variables
self.salary = salary
def set_name(self, new_name): # Method to modify an instance variable.
self.name = new_name
return new_name
alice = Employee('Alice', 150) # Create instances with unique attributes.
tom = Employee('tomnolan', 100)
tom.set_name('tomnolan2') # Modify only tom's name.
print(tom.name) # Output: tomnolan2
print(alice.name) # Output: Alice (alice is not modified)
- Instance variables can be accessed inside the class methods using
self
. - Class variables can be accessed inside the class methods using
cls
.
Accessing Class Variables from Instances
You can use type(instance)
or instance.__class__
to get a reference to the class from an instance:
class Employee():
cls_id = 'employee'
def __init__(self, name, salary):
self.name = name
self.salary = salary
tom = Employee('tomnolan', 100)
# Accessing the class variable through the instance's class:
print(type(tom).cls_id) # Output: employee
print(tom.__class__.cls_id) # Output: employee
- Both
type(tom)
andtom.__class__
will return the class object.