Python不支持函数重载,但是Python3提供了一个装饰器@singledispatch
,用于定义一个泛型函数
@singledispath
装饰器
普通函数中使用
- 示例代码
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
32
33
34
35from 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), "tuple or dict")
show(1)
show("xx")
show([1])
show((1,2,3))
show({"a":"b"})
# Output:
1 <class 'int'> int
xx <class 'str'> str
[1] <class 'list'> obj
(1, 2, 3) <class 'tuple'> tuple or dict
{'a': 'b'} <class 'dict'> tuple or dict
类中使用
- 示例代码:
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
32
33
34
35
36
37from 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)
# Output:
str safly
tuple (1, 2, 3)
list or dict [1, 2, 3]
list or dict {'a': 1}
我可以接受<class 'bool'>类型的参数True