[转]编程语言中的 鸭子模型(duck typing)
在學習Python的時候發(fā)現(xiàn)了鴨子類型這個術語,聽起來好像很有意思一樣,所以把它記下來。
鴨子類型的核心概念在于一個對象的有效語義,不是繼承自特定的類或者實現(xiàn)特定的方法,而是
由當前的屬性和方法集合決定的。聽起來依舊很迷茫,簡單的說:
"當看到一只鳥走起來像鴨子、游泳起來像鴨子、叫起來也像鴨子,那么這只鳥就可以被稱為鴨子。"
在鴨子類型中,關注的不是對象的類型本身,而是它是如何使用的。
?
實際的例子1,將前兩個參數(shù)相加后和第三個參數(shù)相乘:
1 def add_then_multiplication(a, b, c): 2 return (a + b) * c 3 4 print add_then_multiplication(1, 2, 3) 5 print add_then_multiplication([1, 2, 3], [4, 5, 6], 2) 6 print add_then_multiplication('hello', 'world', 9)只要參數(shù)之間支持+和*運算,就在不使用繼承的情況下實現(xiàn)多態(tài)。
?
例子2,鴨子和人:
1 class Duck: 2 def quack(self): 3 print "Quaaaaack..." 4 def feathers(self): 5 print "The Duck has feathers." 6 7 class Person: 8 def quack(self): 9 print "Person is not a duck" 10 def feathers(self): 11 print "The person takes a feather from the ground and shows it." 12 13 def in_the_forest(duck): 14 duck.quack() 15 duck.feathers() 16 17 def game(): 18 donald = Duck() 19 john = Person() 20 in_the_forest(donald) 21 in_the_forest(john) 22 23 game()這個例子中,可以看出來,人不是鴨子,但是一旦擁有的鴨子的一些方法,就可以被當成--鴨子類型。
"在Python中,鴨子類型的最典型例子就是類似file的類。這些類可以實現(xiàn)file的一些或全部方法,并可以用于file通常使用的地方。" 但是一旦一個類不具有鴨子的方法,大概是要出錯的。如:
1 class Duck: 2 def quack(self): 3 print "Quaaaaack..." 4 def feathers(self): 5 print "The Duck has feathers." 6 7 class Person: 8 def quack(self): 9 print "Person is not a duck" 10 def feathers(self): 11 print "The person takes a feather from the ground and shows it." 12 13 class Car: 14 def run(self): 15 print "Car is running" 16 17 def in_the_forest(duck): 18 duck.quack() 19 duck.feathers() 20 21 def game(): 22 donald = Duck() 23 john = Person() 24 in_the_forest(donald) 25 in_the_forest(john) 26 car = Car() 27 try: # will throw exception 28 in_the_forest(car) 29 except (AttributeError, TypeError): 30 print "No the method for duck typing" 31 32 game() 33"在更實際的實現(xiàn)類似file的行為的例子中,人們更傾向于使用Python的異常處理機制來處理各種各樣的可能因為各種程序員無法控制的環(huán)境和operating system問題而發(fā)生的I/O錯誤。在這里,“鴨子類型”產(chǎn)生的異??梢栽谒鼈冏约旱淖泳渲胁东@,與操作系統(tǒng)、I/O和其他可能的錯誤分別處理,從而避開復雜的檢測和錯誤檢查邏輯。"
個人認為:鴨子類型也許能夠避免一些類的重寫,無需大量復制相同的代碼,但是需要良好的文檔支持,不然會讓代碼變得很混亂,誰知道你的鴨子是不是我的鵝呢?哈哈
來自維基百科: 鴨子類型
轉載于:https://www.cnblogs.com/jaw-crusher/p/3475868.html
總結
以上是生活随笔為你收集整理的[转]编程语言中的 鸭子模型(duck typing)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 利用Android中的三大主件来实现一个
- 下一篇: Windows Azure 安全最佳实践