zoukankan      html  css  js  c++  java
  • 多态

    #多态:
    #多态的概念指出了对象如何通过他们共同的属性和动作来操作及访问,而不需要考虑他们具体的类。
    #多态表明了动态绑定的存在,允许重载及运行时类型确定和验证。
    #多态体现在由同一个类实例化出的多个对象,这些对象执行相同的方法时,执行的过程和结果是不一样的。

    #Python中多态的作用
    #让具有不同功能的函数可以使用相同的函数名,这样就可以用一个函数名调用不同内容(功能)的函数。

    #Python
    中多态的特点
    #1、只关心对象的实例方法是否同名,不关心对象所属的类型;
    #2、对象所属的类之间,继承关系可有可无;
    #3、多态的好处可以增加代码的外部调用灵活度,让代码更加通用,兼容性比较强;
    #4、多态是调用方法的技巧,不会影响到类的内部设计。

    #
    多态的应用场景
    #1. 对象所属的类之间没有继承关系
    #2. 对象所属的类之间有继承关系

    #实例1
    class H2o:
    def __init__(self,name,temperature):
    self.name = name
    self.temperature = temperature
    def turn_ic(self):
    if self.temperature < 0:
    print('%s-->温度太低结冰了'%self.name)
    elif self.temperature > 0 and self.temperature < 100:
    print('%s-->液化成水'%self.name)
    else:
    print('%s-->温度太高变成了蒸汽'%self.name)

    class Water(H2o):
    pass
    class Ice(H2o):
    pass
    class Steam(H2o):
    pass
    w1 = Water('',25)
    i1 = Ice('',-20)
    s1 = Steam('蒸汽',120)

    w1.turn_ic()
    i1.turn_ic()
    s1.turn_ic()
    #将实例化对象调用转变为一个函数
    print('-----start函数模式-----')
    def func(obj):
    obj.turn_ic()
    func(w1)
    func(i1)
    func(s1)
    print('-------end---------')
    #实例2
    class Bird:
    def __init__(self,color,name):
    self.color = color
    self.name = name
    def Bird_type(self):
    if self.color == 'red':
    print('这是一只red_bird')
    else:
    print('这是一只other_bird')

    class Small_bird(Bird):
    pass
    class Large_bird(Bird):
    pass
    b1 = Small_bird('red','name1')
    b2 = Large_bird('dark','name2')
    b1.Bird_type()
    b2.Bird_type()

    def Bfunc(obj): #将实例化对象封装成一个函数
    obj.Bird_type()
    Bfunc(b1)
    Bfunc(b2)
    print('-------end---------')
  • 相关阅读:
    HDU1879 kruscal 继续畅通工程
    poj1094 拓扑 Sorting It All Out
    (转)搞ACM的你伤不起
    (转)女生应该找一个玩ACM的男生
    poj3259 bellman——ford Wormholes解绝负权问题
    poj2253 最短路 floyd Frogger
    Leetcode 42. Trapping Rain Water
    Leetcode 41. First Missing Positive
    Leetcode 4. Median of Two Sorted Arrays(二分)
    Codeforces:Good Bye 2018(题解)
  • 原文地址:https://www.cnblogs.com/shadowfolk/p/14655697.html
Copyright © 2011-2022 走看看