[英]Python multimethods using isinstance
Guido van Rossum在本文中說過,這種在Python中的多方法實現:
def foo(a, b):
if isinstance(a, int) and isinstance(b, int):
...code for two ints...
elif isinstance(a, float) and isinstance(b, float):
...code for two floats...
elif isinstance(a, str) and isinstance(b, str):
...code for two strings...
else:
raise TypeError("unsupported argument types (%s, %s)" % (type(a), type(b)))
是“乏味的”和“不是很OO”。 然后,他介紹了如何使用裝飾器來實現多重方法,我認為這些方法如果沒有Python的較深知識,那將是無法訪問的。
我的問題:我需要編寫一個多方法,上面的代碼實際上是什么“不是OO”?
更新 :根據Thomas Orozco的回答,我現在意識到我實際上根本不需要“編寫”多種方法。
與其檢查傳遞給您方法的對象的類型,不如檢查對象的類型,以使對象自己實現邏輯。
讓我們舉個例子: len
函數。
本機實現為:
def len(x):
if type(x) == str:
# compute the length of a string
elif type(x) == list:
# compute the length of a list
else:
#
但這有一些警告
len
就無法在自己的對象中支持len
。 而且,最重要的是,它的面向對象部分意味着它的str
實現分散在代碼庫中:用於計算其長度的代碼在這里,用於對其進行切片的代碼在其他地方...
取而代之的是,Python中使用的設計更為精巧:
def len(x):
return x.__len__()
然后由每個對象自己實現__len__
方法。 len
函數只是詢問對象的長度。
在某種程度上,您可以將其視為“策略模式”
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.