0Pricing
Python Academy · Lesson

@classmethod and @staticmethod

Define class-level and static methods with appropriate decorators.

@classmethod and @staticmethod is a free Python Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Python Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Introduction

@classmethod receives the class as first argument. @staticmethod receives nothing special. Both are defined on the class.

Instance vs Class vs Static

Regular methods get self. Class methods get cls. Static methods get neither. Choose based on what data you need.
class Demo:
    def instance(self): return 'instance'
    @classmethod
    def class_m(cls): return f'class: {cls.__name__}'
    @staticmethod
    def static_m(): return 'static'
d = Demo()
print(d.instance())
print(Demo.class_m())
print(Demo.static_m())

@classmethod as Factory

The most common use: alternative constructors. Date.from_string('2024-01-15') instead of parsing in __init__.
class Date:
    def __init__(self, y,m,d): self.y,self.m,self.d=y,m,d
    @classmethod
    def today(cls):
        from datetime import date
        d = date.today()
        return cls(d.year, d.month, d.day)
    def __repr__(self): return f'{self.y}-{self.m}-{self.d}'
print(Date.today())

@classmethod with Inheritance

cls in a classmethod refers to the actual subclass, not the base class. This makes factory methods work correctly with subclasses.
class Animal:
    @classmethod
    def create(cls, name):
        return cls(name)
    def __init__(self, name): self.name = name
class Dog(Animal): pass
d = Dog.create('Rex')
print(type(d).__name__, d.name)

@staticmethod for Utilities

Static methods are regular functions logically grouped with a class. They cannot access class or instance data.
class MathHelper:
    @staticmethod
    def clamp(value, lo, hi):
        return max(lo, min(hi, value))
print(MathHelper.clamp(15, 0, 10))
print(MathHelper.clamp(-5, 0, 10))

@staticmethod vs Module Function

If a function doesn't need the class, it could be a module-level function. Use @staticmethod only when it logically belongs to the class.
class Validator:
    @staticmethod
    def is_email(s): return '@' in s and '.' in s
print(Validator.is_email('user@example.com'))
print(Validator.is_email('not-an-email'))

Calling from Instance

You can call both @classmethod and @staticmethod on instances, but cls/no-first-arg behavior is unchanged.
class C:
    @classmethod
    def who(cls): return cls.__name__
    @staticmethod
    def pi(): return 3.14
c = C()
print(c.who())
print(c.pi())

Class Method for Singletons

classmethods can enforce singleton patterns by checking if an instance already exists.
class Singleton:
    _instance = None
    @classmethod
    def get(cls):
        if cls._instance is None:
            cls._instance = cls()
        return cls._instance
a = Singleton.get()
b = Singleton.get()
print(a is b)

Overriding Classmethods

A subclass can override a classmethod. cls will then be the subclass, maintaining polymorphism.
class Base:
    @classmethod
    def info(cls): return f'{cls.__name__} info'
class Child(Base): pass
print(Base.info())
print(Child.info())

Type Checking with cls

Inside a classmethod, cls is the actual class. Use cls() to create instances — don't hardcode the class name.
class Shape:
    @classmethod
    def make(cls):
        return cls()  # NOT Shape()
class Square(Shape): pass
print(type(Square.make()).__name__)

Combining with @property

A class-level cached value can combine @classmethod and a class attribute for class-wide caching.
class Config:
    _data = None
    @classmethod
    def load(cls):
        if cls._data is None:
            cls._data = {'debug': True}
        return cls._data
print(Config.load())

Quick Check

What is cls in a @classmethod?

Recap

@classmethod gets cls: use for factories, alternative constructors, singletons. @staticmethod gets nothing: use for utilities. cls is the actual (sub)class.

Keep Going

Excellent progress! Keep going to master the next concept.

Frequently asked questions

Is the “@classmethod and @staticmethod” lesson free?

Yes — the full text of “@classmethod and @staticmethod” is free to read here on the web, and the Python Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Python Academy course, upgrade to CoddyKit PRO.

What will I learn in “@classmethod and @staticmethod”?

Define class-level and static methods with appropriate decorators. You practise Python Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Python Academy?

No prior experience is required. Python Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “@classmethod and @staticmethod” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Python Academy lesson?

Yes. Every Python Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Functions as First-Class Objects
  2. Writing Custom Decorators
  3. The @property Decorator
  4. @classmethod and @staticmethod
← Back to Python Academy