@classmethod
Decorators & Metaclasses

Meaning

A decorator that transforms a method into a class method, receiving the class as its first argument (cls).

Primary Function

Defines a method that receives the class as its first argument, allowing it to be called on the class itself.

Communicative Purpose

Indicates that a method belongs to the class rather than instances, enabling alternative constructors or factory methods.

Pattern

@classmethod

Core Structure

@classmethod

Função primária

Defines a method that receives the class as its first argument, allowing it to be called on the class itself.

Propósito comunicativo

Indicates that a method belongs to the class rather than instances, enabling alternative constructors or factory methods.

Situações de gatilho

When you need a method that operates on the class itself, such as alternative constructors, factory methods, or class-level utilities.

Contextos

Inside a class definition, placed directly above a method definition to indicate it is a class method.

Padrão

@classmethod

Estrutura central

@classmethod

Slots de substituição

<method_name>, <parameters>

Colocados típicos

  • def
  • cls
  • @staticmethod
  • @property

Substituições comuns

  • @staticmethod
  • no decorator

Erros comuns

Using 'self' instead of 'cls' as first argument; forgetting to include 'cls' parameter; applying @classmethod to a function outside a class.

Similar / contraste

@staticmethod (no cls or self), @property (descriptor), instance methods (no decorator)

Interferências

Confusing @classmethod with @staticmethod (which receives neither cls nor self) or with regular instance methods (which receive self).

Família do chunk

  • @staticmethod
  • @property

Nuance

Receives the class as its first argument, enabling alternative constructors and access to class-level state.

Efeito pragmático

Indicates the method is bound to the class, allowing it to be called on the class itself.

Dica de memória

@classmethod decorator for class methods

Upgrade path

Alternative constructors using @classmethod

Tipo de construção: decoratorTag de espaçamento: Long-term

Log in to save chunks.