多态意味着可以对不同的对象使用同样的操作,但它们可能会以多种形态呈现出结果。
在Python中,任何不知道对象到底是什么类型,但又需要对象做点什么的时候,都会用到多态。
方法多态
class calculator:
def count(self,args):
return 1
calc=calculator()
from random import choice
obj=choice(['hello,world',[1,2,3],calc])
print obj
print type(obj)
print obj.count('a')
对于一个临时对象obj,它通过Python的随机函数取出来,不知道具体类型(是字符串、元组还是自定义类型),都可以调用count方法进行计算,至于count由谁(哪种类型)去做怎么去实现我们并不关心。
运算符多态
def add(x,y):
return x+y
print add(1,2) #输出3
print add("hello,","world") #输出hello,world
鸭子类型的多态
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):
duck.quack()
duck.feathers()
def game():
donald = Duck()
john = Person()
in_the_forest(donald) #in_the_forest函数的参数是类的实例。
in_the_forest(john)
game()
就in_the_forest函数而言,参数对象是一个鸭子类型,它实现了方法多态。但是实际上我们知道,从严格的抽象来讲,Person类型和Duck完全风马牛不相及。