Duck typing:是动态类型的一种风格。在这种风格中,一个对象有效的语义,不是由继承自特定的类或实现特定的接口,而是由当前方法和属性的集合决定。在 Duck typing中,关注的不是对象的类型本身,而是它是如何使用的。
Duck typing在Python中被广泛使用。下面是Duck typing的一个典型例子:
class Duck:
def quack(self):
print("Quaaaaaack!")
def feathers(self):
print("The duck has white and gray feathers.")
class Person:
def quack(self):
print("The person imitates a duck.")
def feathers(self):
print("The person takes a feather from the ground and shows it.")
def in_the_forest(duck):
try:
duck.quack()
duck.feathers()
except(AttributeError, TypeError):
print("{} can't quack() or feathers()".format(duck))
def game():
donald = Duck()
john = Person()
in_the_forest(donald)
in_the_forest(john)
in_the_forest("nelson")
if __name__ == '__main__':
game()
Duck typing在不使用继承的情况下使用了多态,具有强可伸缩性。
但如果调用的方法不存在,那么将引发一个运行时错误。通常倾向于用异常处理来处理。异常可以简单地添加到包裹它的代码,并不需要影响更多的代码的逻辑,从而避开复杂的检测和错误检查逻辑。
Duck typing常常被引用的一个批评是:它要求程序员在任何时候都必须很好地理解他/她正在编写的代码。