Nearby lessons
89 of 108Python - Class Methods
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.
Syntax
class Animal:
legs = 4
@classmethod
def walk(cls, name):
print(name, "walks with", cls.legs, "legs")Example
class Test:
count = 0
def __init__(self):
Test.count += 1
@classmethod
def noOfObjects(cls):
print(cls.count)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 |
🧠 Test Your Knowledge
3 QuestionsProgress: 0 / 3
Keep Going!Python - Inheritance