python继承多态

作者 新城 日期 2017-08-24
python继承多态



python 继承

数据封装、继承和多态是面向对象的三大特点

1
2
3
4
5
6
7
8
9
10
11
class Animal(object):   #**定义动物类**
def run(self):
print('Animal is running...')
class Dog(Animal): #定义Dog继承Animal
pass

class Cat(Animal): #定义Cat继承Animal
pass

dog = Dog() #实例化Dog
dog.run() #dog继承 Animal的run方法

哇 比java方便这么多?神奇

1
2
3
4
5
6
7
8
9
class Animal(object):
def run(self):
print('Animal is running...')
class Dog(Animal):
def run(self):
print('Dog is running...')

dog = Dog()
dog.run() #输出Dog is running..

子类和父类有同名方法的时候 ,子类会覆盖父类的方法

a = list() # a是list类型
b = Animal() # b是Animal类型
c = Dog() # c是Dog类型

判断一个变量的类型

1
2
3
4
isinstance(a,list)     #true
isinstance(b, Animal) #true
isinstance(c, Dog) #true
isinstance(c, Animal) #true

c继承了Animal 所以c不仅仅是Dog 还是Animal

多态的好处

要理解多态的好处,我们还需要再编写一个函数

1
2
3
4
5
6
7
8
9
10
11
def run_twice(animal):
animal.run()
animal.run()
#当我们传入Animal的实例时,run_twice()就打印出
run_twice(Animal()) #Animal is running...

#当我们传入Dog的实例时,run_twice()就打印出
run_twice(Dog()) #Dog is running...

#当我们传入Cat的实例时,run_twice()就打印出
run_twice(Cat()) #Cat is running...

1
2
3
4
5
class Tortoise(Animal):     #继承Animal
def run(self):
print('Tortoise is running slowly...')

run_twice(Tortoise) #Tortoise is running slowly...

任何依赖Animal作为参数的函数或者方法都可以不加修改地正常运行,原因就在于多态

小结:

  • 继承可以把父类的所有功能都直接拿过来,这样就不必重零做起,
    子类只需要新增自己特有的方法,也可以把父类不适合的方法覆盖重写
  • 动态语言的鸭子类型特点决定了继承不像静态语言那样是必须的。