python面向对象的三大特性之一多态

多态

多态的特性是调用不同的子类将会产生不同的行为,而无需明确知道这个子类实际上是什么

说白了就是,不同的对象调用相同的方法,产生不同的行为

例如:s1是字符串类型,w1是列表,两个完全不同的对象,他们都可以调用len方法,而得出的结果不同

多态实际上是依附于继承的两种含义:"改变"和"扩展"本身就意味着必须有机制去选用你改变/扩展过的版本,多态实质上就是继承的实现细节

子类实例化后调用基类的方法,w1.turn_ice()叫做多态;

class H20:
    def __init__(self,name,temerature):
        self.name = name
        self.temerature = temerature
    def turn_ice(self):
        if self.temerature < 0:
            print("[%s]温度太低结冰了"%self.name)
        elif self.temerature > 0 and self.temerature < 100:
            print("[%s]液化成水" % self.name)
        elif self.temerature > 100:
            print("[%s]温度太高变成水蒸气" % self.name)
class Water(H20):
    pass
class Ice(H20):
    pass
class Steam(H20):
    pass
w1 = Water("",25)
i1 = Ice("",-20)
s1 = Steam("水蒸气",3000)
w1.turn_ice() #执行过程中不同的对象调用相同的方法
i1.turn_ice()
s1.turn_ice()
#或者定义一个接口来执行上面的调用
def func(obj):
    obj.turn_ice()
func(w1)
func(i1)
func(s1)

 

posted @ 2018-12-08 17:18  叫我大表哥  阅读(259)  评论(0编辑  收藏  举报