Skip to content

Module 11 · Object-Oriented Programming — topic 12 of 25

Class methods

Methods that receive the class (cls) instead of an instance, defined with @classmethod: alternative constructors, factories that respect subclasses, and managing class-level state.

Beginner 10 min read·Lesson 169 of 306 in Python Programming

Learning objectives

  • Define class methods with @classmethod
  • Write alternative constructors that return cls(...)
  • Use class methods to work with class-level data

Definition

A class method is defined with the @classmethod decorator and receives the class itself as its first argument, conventionally named cls. It can be called on the class or on an instance.

Introduction

datetime.date.today() and dict.fromkeys() are class methods: you call them on the class to get a new object, without having one first.

Why it matters

Class methods let a class offer several convenient ways to create objects (from a string, a file, a dictionary) while keeping one real constructor.

Detailed explanation

Decorate the method with @classmethod; its first parameter cls receives the class.

Call it as ClassName.method(...) (most common) or obj.method(...) — cls is still the class.

Alternative constructors parse or convert input and end with return cls(...). Using cls instead of the class name means subclasses get instances of the subclass.

Class methods can also read and update class variables (cls.count += 1).

Prefer a class method over a module function when the operation is clearly about creating or configuring this particular type.

Because a class method doesn't receive an instance, it cannot read instance attributes such as self.name. If a method needs data from a particular object, it should be an ordinary instance method instead.

Syntax

Python
class Date:
def __init__(self, day, month, year):
self.day, self.month, self.year = day, month, year
@classmethod
def from_string(cls, text):
day, month, year = map(int, text.split("/"))
return cls(day, month, year)
d = Date.from_string("27/11/2026")
  • @classmethod receives cls.
  • Return cls(...) for factories.
  • Works correctly with subclasses.

Code examples

An alternative constructor

Python
class Date:
def __init__(self, day, month, year):
self.day, self.month, self.year = day, month, year
@classmethod
def from_string(cls, text):
day, month, year = map(int, text.split("/"))
return cls(day, month, year)
def iso(self):
return f"{self.year:04d}-{self.month:02d}-{self.day:02d}"
print(Date.from_string("27/11/2026").iso())
Output
2026-11-27

Working with class state

Python
class Session:
active = 0
def __init__(self):
Session.active += 1
@classmethod
def report(cls):
return f"{cls.__name__}: {cls.active} active"
Session(); Session()
print(Session.report())
Output
Session: 2 active

More examples

Factories that respect subclasses

Python
class Shape:
def __init__(self, *sides):
self.sides = sides
@classmethod
def from_csv(cls, text):
return cls(*map(float, text.split(",")))
def __repr__(self):
return f"{type(self).__name__}{self.sides}"
class Rectangle(Shape):
def area(self):
w, h = self.sides
return w * h
class Triangle(Shape):
def area(self):
a, b, c = self.sides
s = (a + b + c) / 2
return round((s * (s - a) * (s - b) * (s - c)) ** 0.5, 2)
r = Rectangle.from_csv("3,4")
t = Triangle.from_csv("3,4,5")
print(r, r.area())
print(t, t.area())
Output
Rectangle(3.0, 4.0) 12.0
Triangle(3.0, 4.0, 5.0) 6.0

Step-by-step explanation

  • from_csv is written once, in Shape.
  • Because it calls cls(...), Rectangle.from_csv builds a Rectangle and Triangle.from_csv builds a Triangle.
  • Each subclass then provides its own area method.

Expected output

Running “Factories that respect subclasses” prints exactly:

TextOutput
Rectangle(3.0, 4.0) 12.0
Triangle(3.0, 4.0, 5.0) 6.0

Practical applications

  • datetime.fromisoformat, int.from_bytes, dict.fromkeys.
  • Loading configuration objects: Config.from_file(path).

Best practices

  • Name alternative constructors from_... or parse.
  • Return cls(...) so subclasses work.
  • Keep validation in __init__ and have factories call it.

Common mistakes

Hard-coding the class name in a factory

Avoid

@classmethod
def from_csv(cls, text):
return Shape(*...)

Prefer

@classmethod
def from_csv(cls, text):
return cls(*...)

Using the base class name returns a Shape even when called on a subclass.

Forgetting the decorator

Avoid

def from_string(cls, text): ...

Prefer

@classmethod
def from_string(cls, text): ...

Without @classmethod, Date.from_string('...') passes the string as cls and fails.

Important notes

  • Class methods are inherited like other methods; cls is whichever class they were called on.

Key takeaways

  • @classmethod methods receive the class as cls.
  • They are ideal for alternative constructors.
  • Return cls(...) to support subclasses.

Try it yourself

  1. 1
    Add Point.from_tuple and Point.origin class methods.
  2. 2
    Write Employee.from_dict(data) that builds an employee from a dictionary.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • ModerateWhat is printed?
Practise this topic