python 什么是鸭子类型


什么是鸭子类型?

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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM