使用 functools.singledispatch 可以讓程式更容易閱讀,來看以下2個範例.
測試環境為 CentOS 8 x86_64 , 參考範例 – https://towardsdatascience.com/simplify-your-functions-with-functools-partial-and-singledispatch-b7071f7543bb
Function
[root@localhost ~]# vi fun.py def process_data(data): if isinstance(data, dict): process_dict(data) elif isinstance(data, list): process_list(data) else: print("Unknow type") def process_dict(data: dict): print("Dict is processed") def process_list(data: list): print("List is processed") process_data([1,2,3]) process_data(1) process_data({"a":1 ,"b":2})
執行結果
[root@localhost ~]# python3 fun.py List is processed Unknow type Dict is processed
functools.singledispatch
將上面程式改成使用 singledispatch 這樣就可以做 Function Overloading .
- 使用 decorator @singledispatch 在 function_name.
- 使用 decorator @functio_name.register(Data Type) 依據不同資料型別來完成不同工作.
[root@localhost ~]# vi func.py from functools import singledispatch @singledispatch def process_data(data): print("Unknow type") @process_data.register(dict) def _(data): print("Dict is processed") @process_data.register(list) def _(data): print("List is processed") process_data([1,2,3]) process_data(1) process_data({"a":1 ,"b":2})
執行結果
[root@localhost ~]# python3 func.py List is processed Unknow type Dict is processed
沒有解決問題,試試搜尋本站其他內容