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
- Preferred way to write alternative constructors: Receives
cls, so subclasses inheritfrom_hex()and return instances of the subclass.
REPL Inspect
help(classmethod)
Linked from
Related notes
- tuts/python3/__builtins__/__builtins__ Linked here; links to this page; shared tags: #builtins
- tuts/python3/__builtins__/chr Linked here; links to this page; shared tags: #builtins
- tuts/python3/__builtins__/compile Linked here; links to this page; shared tags: #builtins
- tuts/python3/__builtins__/property Linked here; links to this page; shared tags: #builtins
- tuts/python3/__builtins__/staticmethod Linked here; links to this page; shared tags: #builtins
- tuts/python3/__builtins__/super Linked here; links to this page; shared tags: #builtins
- tuts/python3/__builtins__ links to this page; shared tags: #builtins
- tuts/c/builtins shared tags: #builtins
- tuts/c/builtins/__FILE__ shared tags: #builtins
- tuts/c/builtins/__func__ shared tags: #builtins