多态
1.什么是多态
由不同的类实例化得到的对象,调用同一个方法,执行的逻辑不同。
举例:
class H2O: def __init__(self,type,tem): self.type = type self.tem = tem def turn_ice(self): if self.tem < 0: print('%s,冻成为冰了' % self.tem) elif self.tem >0: print('%s,液化成水了' % self.tem) class Ice(H2O): pass class Water(H2O): pass i1 = Ice('冰',-20) w1 = Water('水',20) def func(obj): obj.turn_ice() func(i1) func(w1)
运行结果:
-20,冻成为冰了 20,液化成水了 Process finished with exit code 0