[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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值