1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > python 什么是鸭子类型

python 什么是鸭子类型

时间:2021-01-07 03:06:49

相关推荐

python 什么是鸭子类型

什么是鸭子类型?

定义:如果走起路来像鸭子,叫起来也像鸭子,那么它就是鸭子(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__方法的对象都可称之为迭代器,本身可以为任何类

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。