220. Duck Typing vs. Structural Typing
🔹 1. Classic Duck Typing Example
class Dog:
def speak(self):
return "Woof!"
class Cat:
def speak(self):
return "Meow!"
def animal_sound(animal):
return animal.speak() # No type checking, relies on method existence
print(animal_sound(Dog())) # ✅ Output: Woof!
print(animal_sound(Cat())) # ✅ Output: Meow!🔹 2. Duck Typing Fails Without Required Methods
class Fish:
def swim(self):
return "I swim"
print(animal_sound(Fish())) # ❌ AttributeError: 'Fish' object has no attribute 'speak'🔹 3. Structural Typing with Protocol (Python 3.8+)
Protocol (Python 3.8+)🔹 4. Runtime Check for Structural Typing
🔹 5. Multiple Method Requirements in Protocol
Protocol🔹 6. Duck Typing with try-except to Handle Missing Methods
try-except to Handle Missing Methods🔹 7. Structural Typing for Function Arguments
🔹 8. Combining Duck Typing & Type Hints
🔹 9. Structural Typing with @staticmethod
@staticmethod🔹 10. Mixing Duck Typing & Structural Typing
🚀 Summary: Duck Typing vs. Structural Typing
💡 When to Use?
Last updated