On this page
  1. classmethod
  2. Import & Availability
  3. Overview & Signature
  4. Usage
  5. Gotchas
  6. REPL Inspect

classmethod

Prev: chr | Up: __builtins__ | Next: compile
Rel: property, staticmethod, super
Ref: docs.python.org — classmethod
Tags: #public #python3 #builtins


Import & Availability

# Built-in (available globally without import)
from builtins import classmethod

Overview & Signature

classmethod(function, /)

Convert a function to be a class method.

Usage

class Color:
    def __init__(self, r: int, g: int, b: int) -> None:
        self.rgb = (r, g, b)

    @classmethod
    def from_hex(cls, code: str):
        code = code.lstrip("#")
        return cls(int(code[0:2], 16), int(code[2:4], 16), int(code[4:6], 16))

assert Color.from_hex("#ff8000").rgb == (255, 128, 0)

Gotchas

REPL Inspect

help(classmethod)

Linked from

Related notes