Nearby lessons
106 of 159Python - Class Methods
📌 What You Will Learn
- Understand what a class method is
- Use the @classmethod decorator
- Know that cls is passed automatically as the first parameter
- Access and modify class variables using cls
What Is a Class Method?
A class method works with class-level data instead of object-level data.
It receives cls as the first parameter, which refers to the class itself.
Syntax
The @classmethod decorator marks a method as a class method.
Example
Class methods are useful for class-level state, such as counting the number of objects created.
Calling Through Object
Like static methods, a class method can be called through an object reference as well as the class name.
Important Points
- Use the
@classmethoddecorator. clsis passed automatically.- Useful for class-level state.
Summary
| Term | Meaning |
|---|---|
| @classmethod | Defines a class method |
| cls | Refers to the class |
| Class variable | Shared across objects |
📝 Key Takeaways
- A class method works with class-level data instead of object-level data
- It is defined using the @classmethod decorator
- cls is passed automatically as the first parameter
- Class methods can access and modify class variables shared by all objects
🧠 Test Your Knowledge
6 QuestionsProgress: 0 / 6