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

函数的使用

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

  

 

相关文章:

  • 2022-12-23
  • 2021-08-12
  • 2021-12-11
  • 2022-12-23
  • 2022-03-07
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-11-28
  • 2022-12-23
  • 2022-12-23
  • 2021-11-30
  • 2022-12-23
  • 2021-05-23
相关资源
相似解决方案