python3中實現函數的重載


var articleDesc = "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
輸出結果為

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM