classmethod Defines Named Constructors
@classmethod factories take strings, dicts, or foreign units and return real instances, and subclasses inherit them because cls is the actual receiver.
Code
class Temperature:
def __init__(self, celsius: float) -> None:
self.celsius = celsius
@classmethod
def from_fahrenheit(cls, fahrenheit: float) -> "Temperature":
# cls 指向真正被调用的类,子类自动继承工厂
return cls((fahrenheit - 32) * 5 / 9)
@classmethod
def from_config(cls, raw: dict) -> "Temperature":
return cls(float(raw["celsius"]))
class Kelvin(Temperature):
pass
for t in (
Temperature(25.0),
Temperature.from_fahrenheit(77),
Temperature.from_config({"celsius": "30"}),
Kelvin.from_fahrenheit(32),
):
print(type(t).__name__, round(t.celsius, 1))Output
Captured from a sandboxed run of this snippet in the build pipeline.
Temperature 25.0
Temperature 25.0
Temperature 30.0
Kelvin 0.0How it works
classmethod Defines Named Constructors comes down to the classes Temperature and Kelvin and the functions __init__, from_fahrenheit and from_config.
The loop for t in ( is the only repeated construct.
What to watch for
- Runs on the standard library alone; nothing to install.
Using it
Signature: def from_fahrenheit(cls, fahrenheit: float) -> "Temperature"
from_fahrenheit is the public entry point; everything else in the file exists to support it.
Inside the computation
def __init__(self, celsius: float) -> None:
self.celsius = celsius
def from_fahrenheit(cls, fahrenheit: float) -> "Temperature":
# cls 指向真正被调用的类,子类自动继承工厂
return cls((fahrenheit - 32) * 5 / 9)
def from_config(cls, raw: dict) -> "Temperature":
return cls(float(raw["celsius"]))
Interactive Tools for This Topic
FAQ
- Does this work in a bare project with no dependencies file?
- Yes — a bare project runs it as-is, since nothing needs declaring. The file defines `__init__`, `from_fahrenheit`, `from_config` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.