[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)
原文地址:https://www.cnblogs.com/iiiiiher/p/8654436.html