python中的多态

# -*- coding: cp936 -*-
#python 27
#xiaodeng
#python中的多态


#多态:一个操作的意义取决于被操作对象的类型,相同的消息给予不同的对象会引发不同的动作。
#多态意味着变量并不知道引用的对象是什么,根据引用对象的不同表现不同的行为方式
#在处理多态对象时,只需要关注他的接口即可
#同一个操作作用于不同的对象,可以有不同的解释,产生不同的执行结果。


#多态案例1
#同样的+号可以用不同的对象相加,体现了多态的功能
print 1+2
print 'hello'+'xiaodeng'
#len()传不同的参数,也体现多态
print 'xiaodeng:',len('xiaodeng')
print '[1,2,3]:',len([1,2,3])



#多态案例2
class Door():
    def open(self):
        return '打开门'

class Windows():
    def open(self):
        return '打开窗户'

class Book():
    def open(self):
        return '打开书'

lst=[Door(),Windows(),Book()]
for item in lst:
    print item.open()


#多态案例3
class Animal():
    def __init__(self,name):
        self.name=name
    def talk(self):
        raise NotImplementedError('method')

class Cat(Animal):
    def talk(self):
        return 'new'
    
class Dog(Animal):
    def talk(self):
        return 'xiaodeng'

animals=[Cat('missy'),Cat('Mr'),Dog('xiaohuang')]
for animal in animals:
    print animal.name+':'+animal.talk()

 

posted @ 2015-10-21 10:21  Xiao|Deng  阅读(1036)  评论(0编辑  收藏  举报