Python 中的單分派泛函數(shù)你真的了解嗎
泛型,如果你學過Java ,應該對它不陌生吧。但你可能不知道在 Python 中(3.4+ ),也可以實現(xiàn)簡單的泛型函數(shù)。
在Python中只能實現(xiàn)基于單個(第一個)參數(shù)的數(shù)據(jù)類型來選擇具體的實現(xiàn)方式,官方名稱 是 single-dispatch。你或許聽不懂,說簡單點,就是可以實現(xiàn)第一個參數(shù)的數(shù)據(jù)類型不同,其調(diào)用的函數(shù)也就不同。
singledispatch 是 PEP443 中引入的,如果你對此有興趣,PEP443 應該是最好的學習文檔:
https://www.python.org/dev/peps/pep-0443/
A generic function is composed of multiple functions implementing the same operation for different types. Which implementation should be used during a call is determined by the dispatch algorithm. When the implementation is chosen based on the type of a single argument, this is known as single dispatch.
它使用方法極其簡單,只要被singledispatch 裝飾的函數(shù),就是一個單分派的(single-dispatch )的泛函數(shù)(generic functions)。
單分派:根據(jù)一個參數(shù)的類型,以不同方式執(zhí)行相同的操作的行為。
多分派:可根據(jù)多個參數(shù)的類型選擇專門的函數(shù)的行為。
泛函數(shù):多個函數(shù)綁在一起組合成一個泛函數(shù)。
這邊舉個簡單的例子,介紹一下使用方法
from functools import singledispatch
@singledispatch
def age(obj):
print('請傳入合法類型的參數(shù)!')
@age.register(int)
def _(age):
print('我已經(jīng){}歲了。'.format(age))
@age.register(str)
def _(age):
print('I am {} years old.'.format(age))
age(23) # int
age('twenty three') # str
age(['23']) # list
執(zhí)行結果
我已經(jīng)23歲了。
I am twenty three years old.
請傳入合法類型的參數(shù)!
說起泛型,其實在 Python 本身的一些內(nèi)建函數(shù)中并不少見,比如 len() , iter(),copy.copy() ,pprint() 等
你可能會問,它有什么用呢?實際上真沒什么用,你不用它或者不認識它也完全不影響你編碼。
我這里舉個例子,你可以感受一下。
大家都知道,Python 中有許許多的數(shù)據(jù)類型,比如 str,list, dict, tuple 等,不同數(shù)據(jù)類型的拼接方式各不相同,所以我這里我寫了一個通用的函數(shù),可以根據(jù)對應的數(shù)據(jù)類型對選擇對應的拼接方式拼接,而且不同數(shù)據(jù)類型我還應該提示無法拼接。以下是簡單的實現(xiàn)。
def check_type(func):
def wrapper(*args):
arg1, arg2 = args[:2]
if type(arg1) != type(arg2):
return '【錯誤】:參數(shù)類型不同,無法拼接!!'
return func(*args)
return wrapper
@singledispatch
def add(obj, new_obj):
raise TypeError
@add.register(str)
@check_type
def _(obj, new_obj):
obj += new_obj
return obj
@add.register(list)
@check_type
def _(obj, new_obj):
obj.extend(new_obj)
return obj
@add.register(dict)
@check_type
def _(obj, new_obj):
obj.update(new_obj)
return obj
@add.register(tuple)
@check_type
def _(obj, new_obj):
return (*obj, *new_obj)
print(add('hello',', world'))
print(add([1,2,3], [4,5,6]))
print(add({'name': 'wangbm'}, {'age':25}))
print(add(('apple', 'huawei'), ('vivo', 'oppo')))
# list 和 字符串 無法拼接
print(add([1,2,3], '4,5,6'))
輸出結果如下
hello, world
[1, 2, 3, 4, 5, 6]
{'name': 'wangbm', 'age': 25}
('apple', 'huawei', 'vivo', 'oppo')
【錯誤】:參數(shù)類型不同,無法拼接!!
如果不使用singledispatch 的話,你可能會寫出這樣的代碼。
def check_type(func):
def wrapper(*args):
arg1, arg2 = args[:2]
if type(arg1) != type(arg2):
return '【錯誤】:參數(shù)類型不同,無法拼接!!'
return func(*args)
return wrapper
@check_type
def add(obj, new_obj):
if isinstance(obj, str) :
obj += new_obj
return obj
if isinstance(obj, list) :
obj.extend(new_obj)
return obj
if isinstance(obj, dict) :
obj.update(new_obj)
return obj
if isinstance(obj, tuple) :
return (*obj, *new_obj)
print(add('hello',', world'))
print(add([1,2,3], [4,5,6]))
print(add({'name': 'wangbm'}, {'age':25}))
print(add(('apple', 'huawei'), ('vivo', 'oppo')))
# list 和 字符串 無法拼接
print(add([1,2,3], '4,5,6'))
輸出如下
hello, world
[1, 2, 3, 4, 5, 6]
{'name': 'wangbm', 'age': 25}
('apple', 'huawei', 'vivo', 'oppo')
【錯誤】:參數(shù)類型不同,無法拼接!!
以上是我個人的一些理解,如有誤解誤傳,還請你后臺留言幫忙指正!
以上就是Python 中的單分派泛函數(shù)你真的了解嗎的詳細內(nèi)容,更多關于Python單分派泛函數(shù)的資料請關注腳本之家其它相關文章!
相關文章
django通過ajax發(fā)起請求返回JSON格式數(shù)據(jù)的方法
這篇文章主要介紹了django通過ajax發(fā)起請求返回JSON格式數(shù)據(jù)的方法,較為詳細的分析了django處理ajax請求的技巧,需要的朋友可以參考下2015-06-06
GitHub 熱門:Python 算法大全,Star 超過 2 萬
4 月 27 日,GitHub 趨勢榜第 3 位是一個用 Python 編碼實現(xiàn)的算法庫,Star 數(shù)早已達到 26000+2019-04-04
Python實現(xiàn)網(wǎng)絡端口轉(zhuǎn)發(fā)和重定向的方法
這篇文章主要介紹了Python實現(xiàn)網(wǎng)絡端口轉(zhuǎn)發(fā)和重定向的方法,結合實例形式分析了Python基于threading和socket模塊實現(xiàn)端口轉(zhuǎn)發(fā)與重定向的具體操作技巧,需要的朋友可以參考下2016-09-09
Python實現(xiàn)批量讀取word中表格信息的方法
這篇文章主要介紹了Python實現(xiàn)批量讀取word中表格信息的方法,可實現(xiàn)針對word文檔的讀取功能,具有一定參考借鑒價值,需要的朋友可以參考下2015-07-07
python實現(xiàn)與Oracle數(shù)據(jù)庫交互操作示例
這篇文章主要為大家介紹了python實現(xiàn)與Oracle數(shù)據(jù)庫交互操作示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家,多多進步,早日升職加薪2021-10-10
Python實現(xiàn)音頻添加數(shù)字水印的示例詳解
數(shù)字水印技術可以將隱藏信息嵌入到音頻文件中而不明顯影響音頻質(zhì)量,下面小編將介紹幾種在Python中實現(xiàn)音頻數(shù)字水印的方法,希望對大家有所幫助2025-04-04
Python實用工具之實現(xiàn)PDF轉(zhuǎn)DOCX文檔
pdf2docx作為第三方包,提供了非常優(yōu)秀的功能,僅僅幾行代碼就可以完成PDF轉(zhuǎn)換為DOCX的工作,所以本文就來利用pdf2docx實現(xiàn)PDF轉(zhuǎn)DOCX文檔功能吧2023-12-12
python數(shù)據(jù)可視化matplotlib繪制折線圖示例
這篇文章主要為大家介紹了python數(shù)據(jù)可視化matplotlib繪制折線圖的示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-06-06

