Skip to content

Commit 3bddbfa

Browse files
authored
练习面向对象的继承和多态
1 parent ef9099e commit 3bddbfa

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

test18.py

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
4+
'练习面向对象的继承和多态'
5+
6+
__author__ = 'sergiojune'
7+
8+
9+
class Animal(object):
10+
def run(self):
11+
print('animal is running')
12+
13+
14+
# 继承Animal类
15+
class Dog(Animal):
16+
# 重载父类的方法
17+
def run(self):
18+
print('Dog is running')
19+
20+
21+
class Cat(Animal):
22+
def run(self):
23+
print('cat is running')
24+
25+
26+
def run_twich(animal):
27+
animal.run()
28+
animal.run()
29+
30+
31+
animal = Animal()
32+
dog = Dog()
33+
cat = Cat()
34+
# 类继承了Animal,所以类中不需要实现任何东西都可以有父类方法
35+
animal.run()
36+
dog.run()
37+
cat.run()
38+
# 这个方法只要是有run方法都可以运行,这就是多态的实现
39+
# 看起来像鸭子,走起路来像鸭子,那这个就是鸭子,这就是鸭子类型,动态语言的鸭子类型
40+
run_twich(animal)
41+
run_twich(dog)
42+
run_twich(cat)

0 commit comments

Comments
 (0)