• 技术文章 >Python技术 >Python基础教程

    python 重载内置函数吗

    爱喝马黛茶的安东尼爱喝马黛茶的安东尼2019-09-21 17:44:16原创2577

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

    相关推荐:《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
    专题推荐:python 重载 内置函数
    品易云
    上一篇:python 判断变量是数字型还是字符型 下一篇:python 头文件怎么写

    相关文章推荐

    • Python对象类型判断与函数重载• python类重载吗• python函数重载吗

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网