多态
多态
多态的概念指出了对象如何通过他们共同的属性和动作来操作及访问,而不必考虑他们具体的类
(不同的对象使用同样的方法)
多态实际上是依附于继承的,是继承的实现细节。
多态,一句话概括:同一个方法,不同对象调用该方法,实现的功能不一样,最直观的例子就是python中的”+”运算方法,在数字相加时,1+2=3,是正常意义上的加法,但是,’a’ + ‘b’ = ‘ab’,就是字符串的拼接,用在列表上:[1] + [2] = [1, 2],就是列表拼接;
同样的方法名,用在不同对象上,实现的功能完全不一样,这就是多态;
多态在python很常见,只是我们很难去注意到它,例如乘法运算符*,正常乘法:1*2=2,字符串乘法:’-‘*5 => ‘—–’;模运算:10%3=1,字符串格式化:’hello %s’ % ‘python’。 --------------------- 作者:simuLeo 来源:CSDN 原文:https://blog.csdn.net/simuLeo/article/details/80067619 版权声明:本文为博主原创文章,转载请附上博文链接!
#_*_coding:utf-8_*_ __author__ = 'Linhaifeng' class H2O: def __init__(self,name,temperature): self.name=name self.temperature=temperature def turn_ice(self): if self.temperature < 0: print('[%s]温度太低结冰了' %self.name) elif self.temperature > 0 and self.temperature < 100: print('[%s]液化成水' %self.name) elif self.temperature > 100: print('[%s]温度太高变成了水蒸气' %self.name) def aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(self): pass class Water(H2O): pass class Ice(H2O): pass class Steam(H2O): 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) #---->w1.turn_ice() func(i1) #---->i1.turn_ice()