什么是鸭子类型?
定义:如果走起路来像鸭子,叫起来也像鸭子,那么它就是鸭子(If it walks like a duck and quacks like a duck, it must be a duck)
鸭子类型是编程语言中动态类型语言中的一种设计风格,一个对象的特征不是由父类决定,而是通过对象的方法决定的。
代码如下
# -*- coding:utf8 -*-# /usr/bin/env pythonfrom collections import Iterablefrom collections import Iteratorclass b(str):passclass a(b):passclass MyIterator(a):def __iter__(self):passdef __next__(self):passprint(isinstance(MyIterator(), Iterable))print(isinstance(MyIterator(), Iterator))print(isinstance(MyIterator(), str))
例如迭代器,我们并不需要继承Iterable或者Iterator,只需要实现__iter__
和__next__
方法的对象都可称之为迭代器,本身可以为任何类