Python多态
1. 多态
关于多态,多态就是上面两种方式的结合,通过多态我们可以写出各种各样的程序。
看下图:
多态即一个方法在父类和子类中存在着不同种用法,可以分别调用。
看下面的例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | class Base: def __init__(self,name): self.name =name print( '%s会读书' %self.name) def reading(self): print( '%s在读语文书' %self.name) class Inherit_One(Base): def reading(self): print( '%s在读英语书' %self.name) class Inherit_Two(Base): def reading(self): print( '%s在看漫画书' %self.name) a = Base( 'a' ) a.reading() b = Inherit_One( 'b' ) b.reading() c = Inherit_Two( 'c' ) c.reading() |
输出结果为:
1 2 3 4 5 6 | a会读书 a在读语文书 b会读书 b在读英语书 c会读书 c在看漫画书 |
可以看出每个继承者都重写了reading方法,然后我们在调用这个方法的时候通过不同的类去调用,这种方式可以帮助我们在不同类中定义相同名字的不同方法,看似混乱,但是在我们现实中的各种管理系统当中往往都是离不开多态的使用。