在python中有这么一类方法,定义在某一个类中,如果某一个对象实现了这个方法,而并没有继承于这个类型,但他也称为这个类型,即魔法方法
python本身是基于鸭子类型实现的语言
如下代码
#go语言的接口设计是参考了鸭子类型,和java的接口概念 #什么是鸭子类型,什么是协议 #当看到一只走起来,游泳起来像鸭子,叫起来也像鸭子的鸟,那么把这只鸟叫做鸭子 #采用的是面向对象的类继承 class Animal: def born(self): pass def walk(self): pass class Dog(Animal): pass class Cat(Animal): pass dog = Dog() #dog是不是动物类,实际上dog就是动物类,忽略了鸭子类型,对于用惯面向对象的人来说 #python语言的本身的设计来讲是基于鸭子类型实现的 #Aniaml实际上只是定义了一些方法的名称而已,其他的任何类只要实现了这个Animal里面的方法,那这个类就是Animal类型 from typing import Iterable #实际上list没有继承Iterable类 a = [] print(type(a)) print(isinstance(a,Iterable)) b = tuple() print(type(b)) print(isinstance(b,Iterable)) class Company(object): def __init__(self,employee_list): self.employee = employee_list def __iter__(self): return iter(self.employee) company = Company(["tom","bob","jane"]) if isinstance(company,Iterable): print("company 是 Iterable类型") else: print("company 不是 Iterable类型") for em in company: print(em)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)