• 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()
  • 相关阅读:
    jmap、jhat、jstat、jstack
    jconsole、java VisualVM、jprofiler
    最长递增子序列 dp
    我的眼泪流下来
    理解二级指针的好例子
    离散数学复习————二元关系
    linux的常用命令
    初学Java
    分治法 ----归并排序
    1074 Reversing Linked List
  • 原文地址:https://www.cnblogs.com/dengyg200891/p/4897068.html
Copyright © 2020-2023  润新知