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