-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy path04_polymorphism.py
More file actions
530 lines (403 loc) · 14.6 KB
/
04_polymorphism.py
File metadata and controls
530 lines (403 loc) · 14.6 KB
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
"""
================================================================================
File: 04_polymorphism.py
Topic: Polymorphism in Python
================================================================================
This file demonstrates polymorphism in Python - the ability of different
objects to respond to the same method call in different ways. This is a
core OOP principle that enables flexible and extensible code.
Key Concepts:
- Duck typing
- Method polymorphism
- Operator overloading
- Protocols and ABC
- Practical polymorphism patterns
================================================================================
"""
# -----------------------------------------------------------------------------
# 1. What is Polymorphism?
# -----------------------------------------------------------------------------
# "Many forms" - same interface, different implementations
print("--- What is Polymorphism? ---")
class Dog:
def speak(self):
return "Woof!"
class Cat:
def speak(self):
return "Meow!"
class Duck:
def speak(self):
return "Quack!"
# Same method call, different behavior
animals = [Dog(), Cat(), Duck()]
print("Different animals, same method:")
for animal in animals:
print(f" {type(animal).__name__}: {animal.speak()}")
# -----------------------------------------------------------------------------
# 2. Duck Typing
# -----------------------------------------------------------------------------
# "If it walks like a duck and quacks like a duck, it's a duck"
print("\n--- Duck Typing ---")
class RealDuck:
"""A real duck."""
def quack(self):
return "Quack quack!"
def fly(self):
return "Flap flap, flying!"
class RobotDuck:
"""A robot that acts like a duck."""
def quack(self):
return "Beep boop quack!"
def fly(self):
return "Propellers spinning, ascending!"
class Person:
"""A person pretending to be a duck."""
def quack(self):
return "*Person making quack sounds*"
def fly(self):
return "*Person flapping arms*"
def duck_demo(duck):
"""Demonstrate a duck (or anything duck-like)."""
print(f" {type(duck).__name__}:")
print(f" Quacking: {duck.quack()}")
print(f" Flying: {duck.fly()}")
# All these work because they have the required methods
print("Duck typing demo:")
duck_demo(RealDuck())
duck_demo(RobotDuck())
duck_demo(Person())
# -----------------------------------------------------------------------------
# 3. Method Polymorphism with Inheritance
# -----------------------------------------------------------------------------
print("\n--- Method Polymorphism ---")
class Shape:
"""Base shape class."""
def area(self):
raise NotImplementedError("Subclass must implement area()")
def describe(self):
return f"{self.__class__.__name__} with area {self.area():.2f}"
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
import math
return math.pi * self.radius ** 2
class Triangle(Shape):
def __init__(self, base, height):
self.base = base
self.height = height
def area(self):
return 0.5 * self.base * self.height
# Polymorphism in action
shapes = [
Rectangle(5, 3),
Circle(4),
Triangle(6, 4)
]
print("Shape descriptions:")
for shape in shapes:
print(f" {shape.describe()}")
# Calculate total area polymorphically
total_area = sum(shape.area() for shape in shapes)
print(f"\nTotal area of all shapes: {total_area:.2f}")
# -----------------------------------------------------------------------------
# 4. Operator Overloading
# -----------------------------------------------------------------------------
# Same operators, different behaviors
print("\n--- Operator Overloading ---")
class Vector:
"""A 2D vector with overloaded operators."""
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f"Vector({self.x}, {self.y})"
def __repr__(self):
return self.__str__()
def __add__(self, other):
"""Vector addition: v1 + v2"""
return Vector(self.x + other.x, self.y + other.y)
def __sub__(self, other):
"""Vector subtraction: v1 - v2"""
return Vector(self.x - other.x, self.y - other.y)
def __mul__(self, scalar):
"""Scalar multiplication: v * n"""
return Vector(self.x * scalar, self.y * scalar)
def __rmul__(self, scalar):
"""Reverse multiplication: n * v"""
return self.__mul__(scalar)
def __neg__(self):
"""Negation: -v"""
return Vector(-self.x, -self.y)
def __eq__(self, other):
"""Equality: v1 == v2"""
return self.x == other.x and self.y == other.y
def __abs__(self):
"""Magnitude: abs(v)"""
return (self.x ** 2 + self.y ** 2) ** 0.5
v1 = Vector(3, 4)
v2 = Vector(1, 2)
print(f"v1 = {v1}")
print(f"v2 = {v2}")
print(f"v1 + v2 = {v1 + v2}")
print(f"v1 - v2 = {v1 - v2}")
print(f"v1 * 3 = {v1 * 3}")
print(f"2 * v2 = {2 * v2}")
print(f"-v1 = {-v1}")
print(f"|v1| = {abs(v1)}")
print(f"v1 == Vector(3, 4): {v1 == Vector(3, 4)}")
# -----------------------------------------------------------------------------
# 5. Polymorphism with Built-in Functions
# -----------------------------------------------------------------------------
print("\n--- Built-in Function Polymorphism ---")
class Playlist:
"""A playlist that works with len() and iteration."""
def __init__(self, name):
self.name = name
self.songs = []
def add_song(self, song):
self.songs.append(song)
def __len__(self):
"""Enable len(playlist)"""
return len(self.songs)
def __iter__(self):
"""Enable for song in playlist"""
return iter(self.songs)
def __getitem__(self, index):
"""Enable playlist[index]"""
return self.songs[index]
def __contains__(self, song):
"""Enable 'song' in playlist"""
return song in self.songs
playlist = Playlist("My Favorites")
playlist.add_song("Song A")
playlist.add_song("Song B")
playlist.add_song("Song C")
print(f"Playlist '{playlist.name}':")
print(f" Length: {len(playlist)}")
print(f" First song: {playlist[0]}")
print(f" 'Song B' in playlist: {'Song B' in playlist}")
print(" All songs:")
for song in playlist:
print(f" - {song}")
# -----------------------------------------------------------------------------
# 6. Polymorphic Functions
# -----------------------------------------------------------------------------
print("\n--- Polymorphic Functions ---")
def process_payment(payment_method):
"""
Process any payment method polymorphically.
Any object with a process() method works!
"""
print(f" Processing with {type(payment_method).__name__}...")
return payment_method.process()
class CreditCard:
def __init__(self, card_number):
self.card_number = card_number[-4:] # Last 4 digits
def process(self):
return f"Charged to card ending in {self.card_number}"
class PayPal:
def __init__(self, email):
self.email = email
def process(self):
return f"Payment sent via PayPal ({self.email})"
class CryptoCurrency:
def __init__(self, wallet):
self.wallet = wallet[:8]
def process(self):
return f"Crypto transferred from {self.wallet}..."
# Same function, different payment methods
payment_methods = [
CreditCard("4111111111111234"),
PayPal("user@example.com"),
CryptoCurrency("0x1234567890abcdef")
]
print("Processing payments:")
for method in payment_methods:
result = process_payment(method)
print(f" Result: {result}")
# -----------------------------------------------------------------------------
# 7. Protocols (Informal Interfaces)
# -----------------------------------------------------------------------------
print("\n--- Protocols (Informal Interfaces) ---")
# Python 3.8+ has typing.Protocol for formal protocols
# Here's the concept with duck typing:
class Drawable:
"""Protocol: anything with a draw() method."""
def draw(self):
raise NotImplementedError
class Circle2D:
def draw(self):
return "Drawing a circle: O"
class Square2D:
def draw(self):
return "Drawing a square: □"
class Triangle2D:
def draw(self):
return "Drawing a triangle: △"
class Text2D:
def __init__(self, text):
self.text = text
def draw(self):
return f"Drawing text: '{self.text}'"
def render_canvas(drawables):
"""Render anything that has a draw() method."""
print("Canvas:")
for drawable in drawables:
print(f" {drawable.draw()}")
# All these can be rendered
elements = [Circle2D(), Square2D(), Triangle2D(), Text2D("Hello")]
render_canvas(elements)
# -----------------------------------------------------------------------------
# 8. Polymorphism with Abstract Base Classes
# -----------------------------------------------------------------------------
print("\n--- ABC Polymorphism ---")
from abc import ABC, abstractmethod
class DataExporter(ABC):
"""Abstract base class for data exporters."""
@abstractmethod
def export(self, data):
"""Export data - must be implemented."""
pass
def validate(self, data):
"""Common validation (can be overridden)."""
if not data:
raise ValueError("No data to export")
return True
class JSONExporter(DataExporter):
def export(self, data):
import json
self.validate(data)
return json.dumps(data, indent=2)
class CSVExporter(DataExporter):
def export(self, data):
self.validate(data)
if not data:
return ""
headers = ",".join(data[0].keys())
rows = [",".join(str(v) for v in row.values()) for row in data]
return headers + "\n" + "\n".join(rows)
class XMLExporter(DataExporter):
def export(self, data):
self.validate(data)
xml = "<root>\n"
for item in data:
xml += " <item>\n"
for key, value in item.items():
xml += f" <{key}>{value}</{key}>\n"
xml += " </item>\n"
xml += "</root>"
return xml
# Same data, different formats
sample_data = [
{"name": "Alice", "age": 25},
{"name": "Bob", "age": 30}
]
exporters = [JSONExporter(), CSVExporter(), XMLExporter()]
print("Exporting same data in different formats:")
for exporter in exporters:
print(f"\n{type(exporter).__name__}:")
print(exporter.export(sample_data))
# -----------------------------------------------------------------------------
# 9. Method Dispatch Based on Type
# -----------------------------------------------------------------------------
print("\n--- Type-Based Method Dispatch ---")
from functools import singledispatch
@singledispatch
def process(value):
"""Default processing for unknown types."""
return f"Don't know how to process {type(value).__name__}"
@process.register(int)
def _(value):
"""Process integers."""
return f"Integer: {value * 2}"
@process.register(str)
def _(value):
"""Process strings."""
return f"String: {value.upper()}"
@process.register(list)
def _(value):
"""Process lists."""
return f"List with {len(value)} items"
# Same function name, different behavior based on type
print("Single dispatch polymorphism:")
print(f" process(42): {process(42)}")
print(f" process('hello'): {process('hello')}")
print(f" process([1,2,3]): {process([1,2,3])}")
print(f" process(3.14): {process(3.14)}")
# -----------------------------------------------------------------------------
# 10. Practical Example: Notification System
# -----------------------------------------------------------------------------
print("\n--- Practical Example: Notification System ---")
class NotificationService(ABC):
"""Abstract base for notification services."""
@abstractmethod
def send(self, recipient, message):
"""Send a notification."""
pass
@abstractmethod
def get_status(self):
"""Get service status."""
pass
class EmailNotification(NotificationService):
def __init__(self, smtp_server="mail.example.com"):
self.smtp_server = smtp_server
def send(self, recipient, message):
return f"📧 Email sent to {recipient}: '{message}'"
def get_status(self):
return f"Email service connected to {self.smtp_server}"
class SMSNotification(NotificationService):
def __init__(self, provider="TwilioMock"):
self.provider = provider
def send(self, recipient, message):
return f"📱 SMS sent to {recipient}: '{message[:50]}...'"
def get_status(self):
return f"SMS service using {self.provider}"
class PushNotification(NotificationService):
def __init__(self, app_name="MyApp"):
self.app_name = app_name
def send(self, recipient, message):
return f"🔔 Push notification to {recipient}: '{message}'"
def get_status(self):
return f"Push service for {self.app_name}"
class SlackNotification(NotificationService):
def __init__(self, workspace="MyWorkspace"):
self.workspace = workspace
def send(self, recipient, message):
return f"💬 Slack message to #{recipient}: '{message}'"
def get_status(self):
return f"Slack connected to {self.workspace}"
# Polymorphic notification manager
class NotificationManager:
"""Manages multiple notification services."""
def __init__(self):
self.services = []
def add_service(self, service):
self.services.append(service)
def send_all(self, recipient, message):
"""Send via all services."""
results = []
for service in self.services:
results.append(service.send(recipient, message))
return results
def status(self):
"""Get status of all services."""
return [service.get_status() for service in self.services]
# Create manager and add services
manager = NotificationManager()
manager.add_service(EmailNotification())
manager.add_service(SMSNotification())
manager.add_service(PushNotification())
manager.add_service(SlackNotification())
print("Service status:")
for status in manager.status():
print(f" ✓ {status}")
print("\nSending notification via all channels:")
for result in manager.send_all("user123", "Your order has been shipped!"):
print(f" {result}")