Just like baking cookies—where each variety follows a core recipe but adds its own twist—object-oriented programming (OOP) relies on defining a base class and extending it with specialized subclasses. In this kitchen-style coding lab, you’ll explore inheritance, encapsulation, and polymorphism through the delicious lens of cookies!
🧁 OOP as Baking Styles: Why Cookies?
Picture yourself as a baker crafting three cookie types: Chocolate Chip, Raisin, and Heart-Sprinkle Sugar. Instead of rewriting mixing and baking steps for each, you design a Cookie base class to handle shared logic. Each subclass inherits these basics while adding unique touches—like extra ingredients or adjusted bake times.
This tasty metaphor shines a light on core OOP concepts:
- Inheritance: Reusing core functionality (like dough prep) across subclasses
- Encapsulation: Packaging related data (ingredients) and actions (bake()) together
- Polymorphism: Letting each cookie type execute bake() in its own way
🥣 Base Cookie Dough — The Cookie Class
The bowl of unbaked dough mirrors the Cookie base class—a blank slate with essential properties (bake_time, ingredients) and a default bake() method. Just as all cookies begin with this neutral base, subclasses build atop shared code without redundancy. The simplicity of the image underscores how complexity emerges through later customization, much like OOP hierarchies.
class Cookie:
def __init__(self, bake_time, ingredients):
self.bake_time = bake_time
self.ingredients = ingredients
def bake(self):
print(f"Baking for {self.bake_time} minutes with: {', '.join(self.ingredients)}")
🥄 Adding Mix-Ins — Subclasses
The three topping bowls represent how subclasses customize the base Cookie class. Just as bakers fold in chocolate chips, raisins, or sprinkles to create distinct flavors, each subclass injects its own ingredients and behavior while preserving the core recipe. This mirrors OOP's inheritance (via super()) and polymorphism (via overridden bake() methods).
class ChocolateChip(Cookie):
def __init__(self):
super().__init__(bake_time=12, ingredients=["flour", "sugar", "butter", "chocolate chips"])
def bake(self):
print("Baking a gooey chocolate chip cookie… 🍫")
class Raisin(Cookie):
def __init__(self):
super().__init__(bake_time=15, ingredients=["flour", "sugar", "raisins", "butter"])
def bake(self):
print("Baking a hearty raisin cookie… 🥣")
class HeartSprinkle(Cookie):
def __init__(self):
super().__init__(bake_time=10, ingredients=["flour", "sugar", "butter", "heart sprinkles"])
def bake(self):
print("Baking a sweet heart-sprinkle cookie… ❤️")
🍪 Cookie Assembly Line — Inheritance in Action
The assembly line shows plain dough balls transforming into three distinct cookies - chocolate chip, raisin, and heart-sprinkle. This progression mirrors how inheritance builds specialized subclasses from a common base. Each stage represents:
- The original Cookie class (plain dough)
- Subclass initialization via super() (adding mix-ins)
- Final preparation (method overrides)
def bake_all(cookies):
for cookie in cookies:
cookie.bake() # Single interface, multiple behaviors
🔥 Finished Cookies in the Oven — Polymorphism Result
The oven reveals polymorphism in its tastiest form: identical heat transforms each cookie type differently—chocolate chips melt into golden pools, raisins caramelize, and sprinkles hold their vibrant color. Like Python’s method dispatch, the shared bake() call adapts to each object’s class. The oven acts as the interpreter, executing one instruction (bake()) that produces context-specific results, proving that interface consistency (the baking process) doesn’t mean uniform behavior. This is polymorphism crystallized: one method signature, multiple delicious implementations.
cookies = [ChocolateChip(), Raisin(), HeartSprinkle()] # All subclasses
bake_all(cookies) # Outputs:
# "Baking a gooey chocolate chip cookie... 🍫"
# "Baking a hearty raisin cookie... 🥣"
# "Baking a sweet heart-sprinkle cookie... ❤️"
Tidak ada komentar:
Posting Komentar