0
0
Pythonprogramming~15 mins

Duck typing concept in Python - Mini Project: Build & Apply

Choose your learning style9 modes available
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
Need a 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
Need a 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
Need a 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
Need a hint?

Call the function make_it_quack with both duck and person to see their messages.