鸭子类型
鸭子模式
动态类型语言的一种风格
多态性:向不同对象传递统一信息,不同的对象在接收到信息时,会做出不同反应
接口:标准
在鸭子类型中,不关注对象的类型本身,而是如何使用的
1. 鸭子类型通常不会理会函数参数类型,依赖于文档(告知传递的对象---有对应的方法)
认为控制
鸭子类型(过于灵活)
2. 关注的不是类型,只关注方法和属性
class Duck:
def swim(self):
print('duck swim')
def quack(self):
print('duck quack')
def feather(self):
print('duck has feather')
class Bird:
def swim(self):
print('Bird swim')
def quack(self):
print('Bird quack')
def feather(self):
print('Bird has feather')
class Human:
def swim(self):
print('human like dog swim')
def quack(self):
print('human quack')
def feather(self):
print('human has feather')
def eat(self):
pass
def forest(duck):
'''有swim quack feather的调用'''
duck.swim()
duck.quack()
duck.feather()
def game():
d=Duck()
b=Bird()
h=Human()
forest(d)
forest(b)
forest(h)
game()
duck swim
duck quack
duck has feather
Bird swim
Bird quack
Bird has feather
human like dog swim
human quack
human has feather