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

結果:

1 <class 'int'> int
xx <class 'str'> str
[1] <class 'list'> obj

本文來自 guoqianqian5812 的CSDN 博客 ,全文地址請點擊:https://blog.csdn.net/guoqianqian5812/article/details/75194118?utm_source=copy

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章