什么是鴨子類型?
定義:如果走起路來像鴨子,叫起來也像鴨子,那么它就是鴨子(If it walks like a duck and quacks like a duck, it must be a duck)
鴨子類型是編程語言中動態類型語言中的一種設計風格,一個對象的特征不是由父類決定,而是通過對象的方法決定的。
代碼如下
# -*- coding:utf8 -*- # /usr/bin/env python from collections import Iterable from collections import Iterator class b(str): pass class a(b): pass class MyIterator(a): def __iter__(self): pass def __next__(self): pass print(isinstance(MyIterator(), Iterable)) print(isinstance(MyIterator(), Iterator)) print(isinstance(MyIterator(), str))
例如迭代器,我們並不需要繼承Iterable或者Iterator,只需要實現__iter__
和__next__
方法的對象都可稱之為迭代器,本身可以為任何類