python 重载内置函数吗

544次阅读
没有评论

python

python中是不支持函数重载的,但在python3中提供了这么一个装饰器functools.singledispatch,它叫做单分派泛函数,可以通过它来完成python中函数的重载,让同一个函数支持不同的函数类型,它提供的目的也正是为了解决函数重载的问题。

看下面的例子,应该知道怎么去使用它完成函数的重载。

from functools import singledispatch
@singledispatch
def show(obj):
    print (obj, type(obj), "obj")
@show.register(str)
def _(text):
    print (text, type(text), "str")
@show.register(int)
def _(n):
    print (n, type(n), "int")
show(1)
show("xx")
show([1])

结果:

1 <class 'int'> int
xx <class 'str'> str
[1] <class 'list'> obj
神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2021-07-03发表,共计496字。
新手QQ群:570568346,欢迎进群讨论 Python51学习