← 中文资源

简体中文版本

classmethod 定义命名构造器

@classmethod 工厂接收字符串、字典等不同形态并返回实例;cls 指向真实调用者,子类自动继承这些构造入口,无需逐个重写。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

Temperature 25.0
Temperature 25.0
Temperature 30.0
Kelvin 0.0

实现说明

除了类 Temperature、Kelvin和函数 __init__、from_fahrenheit、from_config,文件里再无其他定义。 驱动整个流程的是 for t in ( 这一个循环。

使用要点

  • 值得导入的表面是 from_fahrenheit;周围的辅助代码对片段是私有的。

常见问题

在一个没有任何依赖声明的空项目里能跑吗?

可以——空项目原样能跑,因为什么都不用声明。 文件在加载时定义 __init__、from_fahrenheit、from_config。

主签名形如 def from_fahrenheit(cls, fahrenheit: float) -> "Temperature"

核心语句

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"]))

代码示例

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))