cls
(argument)
In Python, cls
is a conventional name for the first argument of a class method.
When you define a class method using the @classmethod
decorator, the method’s first argument—which is required—will hold a reference to the class itself. Conventionally, this argument is calls cls
and allows you to use the class object inside the method.
Following this naming convention will make your code Pythonic and familiar to other Python developers.
Example
Here’s an example illustrating the use of cls
in a class method:
demo.py
class DemoClass:
class_variable = "Hello, Class!"
@classmethod
def show_class_variable(cls):
print(cls.class_variable)
# Usage
DemoClass.show_class_variable() # Output: Hello, Class!
In this example, .show_class_variable()
is a class method, and cls
is used to access .class_variable
from the class itself.
Related Resources
Tutorial
Python's Instance, Class, and Static Methods Demystified
In this tutorial, you'll compare Python's instance methods, class methods, and static methods. You'll gain an understanding of when and how to use each method type to write clear and maintainable object-oriented code.
For additional information on related topics, take a look at the following resources:
- Python Classes: The Power of Object-Oriented Programming (Tutorial)
- Object-Oriented Programming (OOP) in Python (Tutorial)
- OOP Method Types in Python: @classmethod vs @staticmethod vs Instance Methods (Course)
- Python's Instance, Class, and Static Methods Demystified (Quiz)
- Class Concepts: Object-Oriented Programming in Python (Course)
- Inheritance and Internals: Object-Oriented Programming in Python (Course)
- Python Classes - The Power of Object-Oriented Programming (Quiz)
- Intro to Object-Oriented Programming (OOP) in Python (Course)
- Object-Oriented Programming (OOP) in Python (Quiz)