0%

多态

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# -*- coding:utf-8 -*-
# @Time :2022/6/21 9:24
# @SOFTWARE :python基础

# 多态:不同的子类对象调用相同的父类方法,得到不同的执行结果

"""
继承 重写
"""

class soldier():
def attack(self):
pass
def retreat(self):
pass

class Army(soldier):
def attack(self):
print("装甲部队")
def retreat(self):
print("跑步撤退")

class Navy(soldier):
def attack(self):
print("驱逐舰")
def retreat(self):
print("跳水")

class AirForce(soldier):
def attack(self):
print("投放原子弹")
def retreat(self):
print("跳伞")

# 创建士兵
obj1 = Army()
obj2 = Navy()
obj3 = AirForce()

lst = [obj1,obj2,obj3]
# => lst = [Army(),Navy(),AirForce()]


strvar = """
将军请下令:
1.全体出击
2.全体撤退
3.海军上,其他撤退
"""
num = input(strvar)
for i in lst:
if num == "1":
i.attack()
if num == "2":
i.retreat()
if num == "3":
if isinstance(i,Navy):
i.attack()
else:
i.retreat()
else:
print("错误指令")