Jump into concepts and practice - no test required
or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Understanding Duck Typing in Python
📖 Scenario: Imagine you are building a simple program that works with different types of objects that can 'quack'. You want to call a quack() method on any object that behaves like a duck, without checking its exact type.
🎯 Goal: You will create two classes with a quack() method, then write a function that accepts any object and calls its quack() method. This shows how duck typing works in Python.
📋 What You'll Learn
Create two classes named Duck and Person.
Each class must have a method called quack() that prints a unique message.
Write a function called make_it_quack that takes one parameter called obj.
Inside make_it_quack, call the quack() method on obj without checking its type.
Create one instance of Duck and one instance of Person.
Call make_it_quack with both instances.
Print the output of each quack() call.
💡 Why This Matters
🌍 Real World
Duck typing is used in Python programs to write flexible code that works with many types of objects as long as they have the needed methods.
💼 Career
Understanding duck typing helps you write cleaner, more adaptable Python code, a valuable skill for software development jobs.
Progress0 / 4 steps
1
Create the Duck and Person classes
Create a class called Duck with a method quack(self) that prints "Quack!". Also create a class called Person with a method quack(self) that prints "I'm pretending to be a duck!".
Python
Hint
Define two classes with the exact names Duck and Person. Each should have a method quack that prints the exact messages.
2
Write the make_it_quack function
Write a function called make_it_quack that takes one parameter called obj. Inside the function, call obj.quack() without checking the type of obj.
Python
Hint
Define a function named make_it_quack that calls quack() on the parameter obj directly.
3
Create instances of Duck and Person
Create a variable called duck and assign it an instance of the Duck class. Create another variable called person and assign it an instance of the Person class.
Python
Hint
Create two variables named exactly duck and person and assign them instances of the classes.
4
Call make_it_quack with both instances and print output
Call make_it_quack with the variable duck. Then call make_it_quack with the variable person. This will print the messages from their quack() methods.
Python
Hint
Call the function make_it_quack with both duck and person to see their messages.
Practice
(1/5)
1. What does duck typing in Python primarily focus on?
easy
A. Using only built-in Python types for safety
B. Checking the exact type of an object before using it
C. Using an object based on its methods and behavior, not its type
D. Restricting objects to a specific class hierarchy
Solution
Step 1: Understand the meaning of duck typing
Duck typing means if an object behaves like a duck (has methods/attributes), it can be used as a duck, regardless of its actual type.
Step 2: Compare options with this meaning
Only Using an object based on its methods and behavior, not its type matches this idea by focusing on behavior, not type checking.
Final Answer:
Using an object based on its methods and behavior, not its type -> Option C
Quick Check:
Duck typing = behavior over type [OK]
Hint: Focus on behavior, not type, to identify duck typing [OK]
Common Mistakes:
Thinking duck typing requires strict type checks
Confusing duck typing with inheritance
Believing duck typing only works with built-in types
2. Which of the following Python code snippets correctly demonstrates duck typing?
easy
A. def quack(duck):
if hasattr(duck, 'quack'):
duck.quack()
class Duck:
def quack(self):
print('Quack!')
quack(Duck())
B. def quack(duck: Duck):
duck.quack()
class Duck:
def quack(self):
print('Quack!')
quack(Duck())
C. def quack(duck):
if type(duck) == Duck:
duck.quack()
class Duck:
def quack(self):
print('Quack!')
quack(Duck())
D. def quack(duck):
duck.quack()
class Duck:
def quack(self):
print('Quack!')
quack(Duck())
Solution
Step 1: Identify duck typing usage
Duck typing means using an object if it has the needed method, without checking its type.
Step 2: Analyze each option
def quack(duck):
if hasattr(duck, 'quack'):
duck.quack()
class Duck:
def quack(self):
print('Quack!')
quack(Duck()) uses hasattr to check for method presence, which fits duck typing. Options B and C check type explicitly, which is not duck typing. def quack(duck):
duck.quack()
class Duck:
def quack(self):
print('Quack!')
quack(Duck()) assumes the object has the method but does not check, which is okay but less safe than A.
Final Answer:
Using hasattr to check method presence before calling -> Option A
Quick Check:
hasattr check = duck typing safe use [OK]
Hint: Look for method presence checks, not type checks [OK]
Common Mistakes:
Confusing type checking with duck typing
Ignoring method presence before calling
Assuming duck typing requires no checks at all
3. What will be the output of the following code?
class Bird:
def fly(self):
print('Flying')
class Airplane:
def fly(self):
print('Jet flying')
objects = [Bird(), Airplane()]
for obj in objects:
obj.fly()
medium
A. Flying\nJet flying
B. Jet flying\nFlying
C. Flying\nFlying
D. Error: fly method not found
Solution
Step 1: Understand the objects and their fly methods
Bird has fly() printing 'Flying', Airplane has fly() printing 'Jet flying'.
Step 2: Trace the loop calling fly on each object
First object is Bird(), prints 'Flying'. Second is Airplane(), prints 'Jet flying'.
Final Answer:
Flying\nJet flying -> Option A
Quick Check:
Each object's fly() runs in order [OK]
Hint: Each object's method runs in loop order [OK]
Common Mistakes:
Assuming type matters for method call
Mixing output order
Expecting error due to different classes
4. Identify the error in this code using duck typing and fix it:
class Cat:
def meow(self):
print('Meow')
def make_sound(animal):
animal.sound()
make_sound(Cat())
medium
A. No error, code runs fine
B. Add a sound() method to Cat class
C. Use type checking before calling sound()
D. Change animal.sound() to animal.meow()
Solution
Step 1: Identify the method called on the object
Function calls animal.sound(), but Cat class has meow(), not sound().
Step 2: Fix the method call to match Cat's method
Change animal.sound() to animal.meow() to call the existing method.
Final Answer:
Change animal.sound() to animal.meow() -> Option D
Quick Check:
Method name must match object's method [OK]
Hint: Match method names exactly when using duck typing [OK]
Common Mistakes:
Calling a method that does not exist
Adding unnecessary type checks
Ignoring method name mismatch
5. You want to write a function process(item) that works with any object having a serialize() method. Which approach best uses duck typing to handle objects without serialize() safely?
hard
A. Check if type(item) == Serializer before calling serialize()
B. Use if hasattr(item, 'serialize'): before calling item.serialize()
C. Wrap item.serialize() call in try-except to catch AttributeError
D. Define a base class with serialize() and inherit all objects from it
Solution
Step 1: Understand duck typing safety
Duck typing uses behavior, so checking method presence with hasattr is a safe way to confirm before calling.
Step 2: Compare options for best practice
Use if hasattr(item, 'serialize'): before calling item.serialize() checks method presence explicitly, fitting duck typing. Wrap item.serialize() call in try-except to catch AttributeError uses try-except but is less clear and may hide other errors. Check if type(item) == Serializer before calling serialize() checks type, which is not duck typing. Define a base class with serialize() and inherit all objects from it requires inheritance, reducing flexibility.
Final Answer:
Use if hasattr(item, 'serialize') before calling item.serialize() -> Option B
Quick Check:
hasattr check = safe duck typing [OK]
Hint: Check method presence with hasattr before calling [OK]