• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
孙龙 程序员
少时总觉为人易,华年方知立业难
博客园    首页    新随笔    联系   管理    订阅  订阅
singledispatch泛函数用法

装饰器,把多个函数绑在一起组成一个泛函数

函数的使用

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

posted on 2019-04-07 20:46  孙龙-程序员  阅读(506)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3