class duck():
def walk(self):
print('I walk like a duck')
def swim(self):
print('i swim like a duck')
class person():
def walk(self):
print('this one walk like a duck')
def swim(self):
print('this man swim like a duck')
def watch_duck(animal):
animal.walk()
animal.swim()
small_duck = duck()
watch_duck(small_duck)
output >>
I walk like a duck
i swim like a duck
duck_like_man = person()
watch_duck(duck_like_man)
output >>
this one walk like a duck
this man swim like a duck
class Lame_Foot_Duck():
def swim(self):
print('i am lame but i can swim')
lame_duck = Lame_Foot_Duck()
watch_duck(lame_duck)
output >>
AttributeError: Lame_Foot_Duck instance has no attribute 'walk'
看例子,传入def watch_duck函数的时候,就默认给了类的方法,如果没有这个方法,函数就会报错
在实际例子中,如果创建了一个类,它含有getitem()方法,那么它就可以看做是一个list类,这就是是所谓的鸭子类型