单分派泛函数

当你的函数想根据不同的参数类型,做不同的操作的时候。python无法做重载,根据参数调用对应的签名函数。一般情况下只能if/elif/else来判断,时间久了,分支会特别多。

使用functools.singledispatch装饰器可以把整体方案拆分成多个模块。甚至可以为你无法修改的类提供专门的函数。使用@singledispatch装饰器装饰的函数会变成泛函数:根据第一个参数的类型,以不同方式执行相同操作的一组函数。

from functools import singledispatch
from collections import abc
import numbers
import html
@singledispatch # @singledispatch 标记处理 object 类型的基函数
def htmlize(obj):
content = html.escape(repr(obj))
return '<pre>{}</pre>'.format(content)
@htmlize.register(str) # 各个专门函数使用 @«base_function».register(«type») 装饰。
def _(text): # 专门函数的名称无关紧要;_ 是个不错的选择,简单明了。
content = html.escape(text).replace('\n', '<br>\n')
return '<p>{0}</p>'.format(content)
@htmlize.register(numbers.Integral) # 为每个需要特殊处理的类型注册一个函数。numbers.Integral 是int 的虚拟超类。
def _(n):
return '<pre>{0} (0x{0:x})</pre>'.format(n)
@htmlize.register(tuple) # 可以叠放多个 register 装饰器,让同一个函数支持不同类型。
@htmlize.register(abc.MutableSequence)
def _(seq):
inner = '</li>\n<li>'.join(htmlize(item) for item in seq)
return '<ul>\n<li>' + inner + '</li>\n</ul>'
posted @   ZeldaLink  阅读(17)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示