Using “cls” in class methods allows you to access class-level methods and variables
2024
Using cls
in class methods allows you to access class-level methods and variables from the class in which the class method is defined, including any methods or variables inherited from parent classes. However, this only applies to class attributes and methods—not instance-specific ones.
Let’s explore how cls
can be used to access both methods and class variables from one class to another using inheritance or direct references. I’ll first explain the standard behavior, and then we’ll see how cls
can help share functionality between the Student
and School
classes.
Example 1: Accessing Class Variables and Methods in Parent-Child Classes
In this example, School
and Student
are in a parent-child relationship where Student
inherits from School
. Using cls
, we can access variables and methods from the Student
class within School
.
class School:
total_students = 0
@classmethod
def increment_student_count(cls):
cls.total_students += 1
@classmethod
def get_total_students(cls):
return cls.total_students
@classmethod
def add_student_to_school(cls, name):
cls.increment_student_count()
return f"{name} has been added to the school."
class Student(School): # Student class inherits from School
@classmethod
def register_student(cls, name):
# We can access School methods via cls in Student
return cls.add_student_to_school(name)
# Student class accesses the School class methods
print(Student.register_student("Alice")) # Output: Alice has been added to the school.
print(School.get_total_students()) # Output: 1
Explanation:
- Class Inheritance: The
Student
class inherits fromSchool
, which means it can access the class-level methods and variables ofSchool
. - Accessing Methods Using
cls
: In theregister_student
method,cls.add_student_to_school(name)
accesses theadd_student_to_school
method defined inSchool
. Sincecls
refers to the class that called the method (in this case,Student
), it allows seamless access to inherited methods and variables. - Variables via
cls
: When we callcls.increment_student_count()
, it updates thetotal_students
variable inSchool
, and this change is reflected across all classes becausetotal_students
is a class variable.
Example 2: Accessing Methods/Variables Across Unrelated Classes (Direct Reference)
If Student
and School
are not related through inheritance, you can still access class methods or variables from one class in another using direct references or passing cls
dynamically.
class School:
total_students = 0
@classmethod
def increment_student_count(cls):
cls.total_students += 1
@classmethod
def get_total_students(cls):
return cls.total_students
@classmethod
def add_student(cls, student_name):
print(f"{student_name} has been added.")
cls.increment_student_count()
class Student:
@classmethod
def register_student(cls, school, name):
# Directly referencing School's method using the school class
school.add_student(name)
# Register a student to a specific school using School's method
Student.register_student(School, "Alice")
print(School.get_total_students()) # Output: 1
Explanation:
- Direct Reference: Here,
Student
andSchool
are unrelated classes. However, we pass theSchool
class into theregister_student
method ofStudent
, allowingStudent
to callSchool
‘sadd_student
method. - Class Methods via Class Reference: By passing
School
as an argument, we can access all its class methods and variables inside theStudent
class method.
Limitations: What Can’t Be Done with cls
?
- Instance Variables and Methods:
cls
can only access class-level variables and methods. If you’re dealing with instance-specific methods or variables, you’ll need an instance of the class to access them. For example:
class School:
def __init__(self, name):
self.name = name
def get_school_name(self):
return self.name
class Student:
@classmethod
def get_school_name(cls, school_instance):
return school_instance.get_school_name()
# Create an instance of School
my_school = School("Green Valley High")
# Pass the school instance to Student class method
print(Student.get_school_name(my_school)) # Output: Green Valley High
- In this case,
cls
cannot be used to access the instance methodget_school_name()
because it’s tied to a specific instance ofSchool
. You need to pass an instance (my_school
) to access instance methods.
Summary:
- Using
cls
, you can access all class-level methods and variables within the class where the class method is defined and any parent classes (through inheritance). - If the classes are unrelated, you can pass the class itself (like
School
) as an argument to another class method (likeStudent
), which allows cross-class access to methods and variables. - However,
cls
cannot access instance methods or instance variables. For instance-specific operations, you must pass an instance of the class.