装饰器,把多个函数绑在一起组成一个泛函数
函数的使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | from functools import singledispatch from collections import abc @singledispatch def show(obj): print (obj, type (obj), "obj" ) #参数字符串 @show .register( str ) def _(text): print (text, type (text), "str" ) #参数int @show .register( int ) def _(n): print (n, type (n), "int" ) #参数元祖或者字典均可 @show .register( tuple ) @show .register( dict ) def _(tup_dic): print (tup_dic, type (tup_dic), "int" ) show( 1 ) show( "xx" ) show([ 1 ]) show(( 1 , 2 , 3 )) show({ "a" : "b" }) |
1 <class 'int'> int
xx <class 'str'> str
[1] <class 'list'> obj
(1, 2, 3) <class 'tuple'> int
{'a': 'b'} <class 'dict'> int
类中使用
from functools import singledispatch class abs: def type(self,args): "" class Person(abs): @singledispatch def type(self,args): super().type("",args) print("我可以接受%s类型的参数%s"%(type(args),args)) @type.register(str) def _(text): print("str",text) @type.register(tuple) def _(text): print("tuple", text) @type.register(list) @type.register(dict) def _(text): print("list or dict", text) Person.type("safly") Person.type((1,2,3)) Person.type([1,2,3]) Person.type({"a":1}) Person.type(Person,True)
1 2 3 4 5 | str safly tuple ( 1 , 2 , 3 ) list or dict [ 1 , 2 , 3 ] list or dict { 'a' : 1 } 我可以接受< class 'bool' >类型的参数 True |
本文来自博客园,作者:孙龙-程序员,转载请注明原文链接:https://www.cnblogs.com/sunlong88/articles/singledispatch.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能