zoukankan      html  css  js  c++  java
  • [py]多态的理解

    多态
    不同的数据类型,执行相同的方法,产生的状态不同

    不同对象调用相同的方法(运行时候的绑定状态)

    #!/usr/bin/env python
    # coding=utf-8
    
    class H2O:
        def __init__(self, name, temp):
            self.name = name
            self.temp = temp
    
        def show(self):
            if self.temp < 0:
                print("%s 温度为: %s" % (self.name, self.temp))
            elif 0 < self.temp < 100:
                print("%s 温度为: %s" % (self.name, self.temp))
            elif self.temp > 100:
                print("%s 温度为: %s" % (self.name, self.temp))
    
    
    class Ice(H2O):
        pass
    
    
    class Water(H2O):
        pass
    
    
    class Stream(H2O):
        pass
    
    
    w1 = Ice("冰", -10)
    w2 = Water("水", 25)
    w3 = Stream("气", 102)
    
    w1.show()
    w2.show()
    w3.show()
    

    系统的多态体现

    str和list都是type类,有共同的父类,都是执行父类的方法,只不过执行时候状态不同.

    >>> s="abc"
    >>> l=[1,2,3]
    >>> s.__len__()
    3
    >>> l.__len__()
    3
    >>>
    
    >>> len(l) ## 调用__len__方法
    3
    >>>
    

    模仿系统len()

    #!/usr/bin/env python
    # coding=utf-8
    
    class H2O:
        def __init__(self, name, temp):
            self.name = name
            self.temp = temp
    
        def show(self):
            if self.temp < 0:
                print("%s 温度为: %s" % (self.name, self.temp))
            elif 0 < self.temp < 100:
                print("%s 温度为: %s" % (self.name, self.temp))
            elif self.temp > 100:
                print("%s 温度为: %s" % (self.name, self.temp))
    
    
    class Ice(H2O):
        pass
    
    
    class Water(H2O):
        pass
    
    
    class Stream(H2O):
        pass
    
    
    w1 = Ice("冰", -10)
    w2 = Water("水", 25)
    w3 = Stream("气", 102)
    
    ## 方法1
    w1.show()
    w2.show()
    w3.show()
    
    ## 方法2: 提供统一api,  类似len(l)
    def func(obj):
        obj.show()
    func(w1)
    func(w2)
    func(w3)
    
  • 相关阅读:
    [HEOI2013]Eden 的新背包问题
    [UOJ#77]A+B Problem
    [CodeForces]786B Legacy
    [LUOGU]P4098[HEOI2013]ALO
    [BZOJ3207]花神的嘲讽计划
    [LUOGU]P2633 Count on a tree
    【东莞市选2007】拦截导弹
    [JZOJ] 3462. 【NOIP2013模拟联考5】休息(rest)
    [BZOJ] 2705: [SDOI2012]Longge的问题
    [BZOJ] 1191: [HNOI2006]超级英雄Hero
  • 原文地址:https://www.cnblogs.com/iiiiiher/p/8654436.html
Copyright © 2011-2022 走看看