
python 继承
1 | class Animal(object): #**定义动物类** |
哇 比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
4isinstance(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
11def 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 | class Tortoise(Animal): #继承Animal |
任何依赖Animal作为参数的函数或者方法都可以不加修改地正常运行,原因就在于多态
小结:
- 继承可以把父类的所有功能都直接拿过来,这样就不必重零做起,
子类只需要新增自己特有的方法,也可以把父类不适合的方法覆盖重写 - 动态语言的鸭子类型特点决定了继承不像静态语言那样是必须的。