python的多态

#多态是不同的子类对象调用相同的父类方法,产生不同的执行结果,可以拯救代码的外部调用的灵活度

#多态以继承和重写的父类方法为前提

#多态是调用方法的技巧,不会影响到类的内部设计。

 1 class FooParent(object):
 2     def __init__(self):
 3         self.parent = 'I\'m the parent.'
 4         print('Parent')
 5 
 6 
 7     def bar(self,message):
 8         print('%s from Parent'%message)
 9 
10 
11 
12 class FooChild(FooParent):
13     def __init__(self):
14         super(FooChild,self).__init__()
15         print('Child')
16 
17     def bar(self,message):
18         super(FooChild,self).bar(message)
19         print('Child bar function')
20         print(self.parent)
21 
22 if __name__ == '__main__':
23     fooChild = FooChild()  #实例化
24     fooChild.bar('HelloWorld')

执行结果:

猜你喜欢

转载自www.cnblogs.com/ymany/p/9771375.html