实现说明
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()