什么是鸭子类型?
定义:如果走起路来像鸭子,叫起来也像鸭子,那么它就是鸭子(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__方法的对象都可称之为迭代器,本身可以为任何类
转载于:https://www.cnblogs.com/KK150713/p/11175850.html