← 中文资源

简体中文版本

singledispatchmethod 分派类方法

用 singledispatchmethod 按参数类型注册重载,通过类实例分派,并为未知类型保留基础实现。

阅读英文原文

运行结果

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

int:42
str:HELLO
list:[int:1, str:A, unsupported:float]
unsupported:dict

实现说明

singledispatchmethod 分派类方法可以归结为类 Formatter和函数 format、_format_int、_format_list、_format_str。

使用要点

  • 运行整个文件:main 会依次驱动 format。

常见问题

「singledispatchmethod 分派类方法」这个示例怎么运行?

把它当完整程序编译/解释运行即可——不需要先安装任何东西。

签名一览:def format(self, value: object) -> str

核心语句

def main() -> None:
    formatter = Formatter()
    print(formatter.format(42))
    print(formatter.format("hello"))
    print(formatter.format([1, "a", 2.5]))
    print(formatter.format({"x": 1}))
def _format_list(self, value: list) -> str:
    parts = [self.format(item) for item in value]
    return "list:[" + ", ".join(parts) + "]"
def _format_int(self, value: int) -> str:
    return "int:" + str(value)

代码示例

from functools import singledispatchmethod


class Formatter:
    @singledispatchmethod
    def format(self, value: object) -> str:
        return "unsupported:" + type(value).__name__

    @format.register(int)
    def _format_int(self, value: int) -> str:
        return "int:" + str(value)

    @format.register(list)
    def _format_list(self, value: list) -> str:
        parts = [self.format(item) for item in value]
        return "list:[" + ", ".join(parts) + "]"

    @format.register(str)
    def _format_str(self, value: str) -> str:
        return "str:" + value.upper()


def main() -> None:
    formatter = Formatter()
    print(formatter.format(42))
    print(formatter.format("hello"))
    print(formatter.format([1, "a", 2.5]))
    print(formatter.format({"x": 1}))


if __name__ == "__main__":
    main()