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.

Loading editor…

Example

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

Loading editor…

Calling Through Object

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

Loading editor…

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

Finished this lesson?

Mark it as complete to track your progress and see technology completion stats.