Nearby lessons

106 of 159

Python - 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.

🐍Code Cell
1class Animal:
2 legs = 4
3 
4 @classmethod
5 def walk(cls, name):
6 print(name, "walks with", cls.legs, "legs")
Output
No output captured.

Example

Class methods are useful for class-level state, such as counting the number of objects created.

🐍Code Cell
1class Test:
2 count = 0
3 
4 def __init__(self):
5 Test.count += 1
6 
7 @classmethod
8 def noOfObjects(cls):
9 print(cls.count)
10 
11 
12t1 = Test()
13t2 = Test()
14t3 = Test()
15 
16Test.noOfObjects()
Output
3

Calling Through Object

Like static methods, a class method can be called through an object reference as well as the class name.

🐍Code Cell
1class Student:
2 college = "ABC College"
3 
4 @classmethod
5 def showCollege(cls):
6 print(cls.college)
7 
8 
9s = Student()
10s.showCollege()
Output
ABC College

Important Points

  • Use the @classmethod decorator.
  • cls is passed automatically.
  • Useful for class-level state.

Summary

Term Meaning
@classmethodDefines a class method
clsRefers to the class
Class variableShared 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 Questions
Progress: 0 / 6