Nearby lessons

89 of 108

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

🧠 Test Your Knowledge

3 Questions

Progress: 0 / 3
Keep Going!Python - Inheritance