1+ #!/usr/bin/env python3
2+ # -*- coding: utf-8 -*-
3+ """
4+ 多态的基本概念和原理
5+
6+ 多态(Polymorphism)是面向对象编程的三大特性之一(封装、继承、多态)。
7+ 多态允许不同类的对象对同一消息做出响应,但具体的响应方式可以不同。
8+
9+ 核心概念:
10+ 1. 同一个接口,不同的实现
11+ 2. 运行时决定调用哪个方法
12+ 3. 提高代码的灵活性和可扩展性
13+ """
14+
15+ # 1. 基本多态示例
16+ class Animal :
17+ """动物基类"""
18+ def __init__ (self , name ):
19+ self .name = name
20+
21+ def make_sound (self ):
22+ """发出声音 - 基类方法"""
23+ pass
24+
25+ def move (self ):
26+ """移动方式 - 基类方法"""
27+ pass
28+
29+ class Dog (Animal ):
30+ """狗类"""
31+ def make_sound (self ):
32+ return f"{ self .name } 汪汪叫"
33+
34+ def move (self ):
35+ return f"{ self .name } 在地上跑"
36+
37+ class Cat (Animal ):
38+ """猫类"""
39+ def make_sound (self ):
40+ return f"{ self .name } 喵喵叫"
41+
42+ def move (self ):
43+ return f"{ self .name } 轻巧地走路"
44+
45+ class Bird (Animal ):
46+ """鸟类"""
47+ def make_sound (self ):
48+ return f"{ self .name } 啾啾叫"
49+
50+ def move (self ):
51+ return f"{ self .name } 在天空中飞翔"
52+
53+ # 2. 多态的使用
54+ def animal_behavior (animal ):
55+ """展示动物行为 - 多态函数"""
56+ print (f"动物名称: { animal .name } " )
57+ print (f"声音: { animal .make_sound ()} " )
58+ print (f"移动: { animal .move ()} " )
59+ print ("-" * 30 )
60+
61+ # 3. 多态在列表中的应用
62+ def demonstrate_polymorphism ():
63+ """演示多态的基本概念"""
64+ print ("=== 多态基本概念演示 ===" )
65+
66+ # 创建不同类型的动物对象
67+ animals = [
68+ Dog ("旺财" ),
69+ Cat ("咪咪" ),
70+ Bird ("小鸟" ),
71+ Dog ("大黄" ),
72+ Cat ("加菲" )
73+ ]
74+
75+ # 多态:同一个函数处理不同类型的对象
76+ for animal in animals :
77+ animal_behavior (animal )
78+
79+ # 4. 多态的优势示例
80+ class Shape :
81+ """形状基类"""
82+ def area (self ):
83+ """计算面积"""
84+ raise NotImplementedError ("子类必须实现area方法" )
85+
86+ def perimeter (self ):
87+ """计算周长"""
88+ raise NotImplementedError ("子类必须实现perimeter方法" )
89+
90+ class Rectangle (Shape ):
91+ """矩形类"""
92+ def __init__ (self , width , height ):
93+ self .width = width
94+ self .height = height
95+
96+ def area (self ):
97+ return self .width * self .height
98+
99+ def perimeter (self ):
100+ return 2 * (self .width + self .height )
101+
102+ def __str__ (self ):
103+ return f"矩形(宽:{ self .width } , 高:{ self .height } )"
104+
105+ class Circle (Shape ):
106+ """圆形类"""
107+ def __init__ (self , radius ):
108+ self .radius = radius
109+
110+ def area (self ):
111+ return 3.14159 * self .radius ** 2
112+
113+ def perimeter (self ):
114+ return 2 * 3.14159 * self .radius
115+
116+ def __str__ (self ):
117+ return f"圆形(半径:{ self .radius } )"
118+
119+ class Triangle (Shape ):
120+ """三角形类"""
121+ def __init__ (self , a , b , c ):
122+ self .a = a
123+ self .b = b
124+ self .c = c
125+
126+ def area (self ):
127+ # 使用海伦公式计算面积
128+ s = (self .a + self .b + self .c ) / 2
129+ return (s * (s - self .a ) * (s - self .b ) * (s - self .c )) ** 0.5
130+
131+ def perimeter (self ):
132+ return self .a + self .b + self .c
133+
134+ def __str__ (self ):
135+ return f"三角形(边长:{ self .a } , { self .b } , { self .c } )"
136+
137+ def calculate_shapes_info (shapes ):
138+ """计算形状信息 - 展示多态的优势"""
139+ print ("\n === 形状计算演示(多态优势) ===" )
140+ total_area = 0
141+ total_perimeter = 0
142+
143+ for shape in shapes :
144+ area = shape .area ()
145+ perimeter = shape .perimeter ()
146+ total_area += area
147+ total_perimeter += perimeter
148+
149+ print (f"{ shape } :" )
150+ print (f" 面积: { area :.2f} " )
151+ print (f" 周长: { perimeter :.2f} " )
152+ print ()
153+
154+ print (f"总面积: { total_area :.2f} " )
155+ print (f"总周长: { total_perimeter :.2f} " )
156+
157+ # 5. 多态与类型检查
158+ def demonstrate_type_checking ():
159+ """演示多态中的类型检查"""
160+ print ("\n === 多态与类型检查 ===" )
161+
162+ dog = Dog ("小白" )
163+ cat = Cat ("小黑" )
164+
165+ # isinstance检查
166+ print (f"dog是Animal的实例: { isinstance (dog , Animal )} " )
167+ print (f"cat是Animal的实例: { isinstance (cat , Animal )} " )
168+ print (f"dog是Dog的实例: { isinstance (dog , Dog )} " )
169+ print (f"cat是Dog的实例: { isinstance (cat , Dog )} " )
170+
171+ # hasattr检查方法是否存在
172+ print (f"dog有make_sound方法: { hasattr (dog , 'make_sound' )} " )
173+ print (f"cat有make_sound方法: { hasattr (cat , 'make_sound' )} " )
174+
175+ # 6. 多态的实际应用场景
176+ class PaymentProcessor :
177+ """支付处理器基类"""
178+ def process_payment (self , amount ):
179+ raise NotImplementedError ("子类必须实现process_payment方法" )
180+
181+ class CreditCardProcessor (PaymentProcessor ):
182+ """信用卡支付处理器"""
183+ def process_payment (self , amount ):
184+ return f"使用信用卡支付 { amount } 元"
185+
186+ class AlipayProcessor (PaymentProcessor ):
187+ """支付宝支付处理器"""
188+ def process_payment (self , amount ):
189+ return f"使用支付宝支付 { amount } 元"
190+
191+ class WechatPayProcessor (PaymentProcessor ):
192+ """微信支付处理器"""
193+ def process_payment (self , amount ):
194+ return f"使用微信支付 { amount } 元"
195+
196+ def process_order (processor , amount ):
197+ """处理订单 - 多态应用"""
198+ result = processor .process_payment (amount )
199+ print (f"订单处理结果: { result } " )
200+
201+ def demonstrate_payment_polymorphism ():
202+ """演示支付系统中的多态应用"""
203+ print ("\n === 支付系统多态应用 ===" )
204+
205+ # 不同的支付方式
206+ processors = [
207+ CreditCardProcessor (),
208+ AlipayProcessor (),
209+ WechatPayProcessor ()
210+ ]
211+
212+ amount = 100
213+ for processor in processors :
214+ process_order (processor , amount )
215+
216+ if __name__ == "__main__" :
217+ # 演示多态的基本概念
218+ demonstrate_polymorphism ()
219+
220+ # 演示形状计算中的多态
221+ shapes = [
222+ Rectangle (5 , 3 ),
223+ Circle (4 ),
224+ Triangle (3 , 4 , 5 ),
225+ Rectangle (2 , 8 )
226+ ]
227+ calculate_shapes_info (shapes )
228+
229+ # 演示类型检查
230+ demonstrate_type_checking ()
231+
232+ # 演示支付系统中的多态
233+ demonstrate_payment_polymorphism ()
234+
235+ print ("\n === 多态的核心要点 ===" )
236+ print ("1. 同一接口,不同实现" )
237+ print ("2. 运行时动态绑定" )
238+ print ("3. 提高代码灵活性和可扩展性" )
239+ print ("4. 降低代码耦合度" )
240+ print ("5. 支持开闭原则(对扩展开放,对修改封闭)" )
0 commit comments