Challenge - 5 Problems
Duck Typing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this duck typing example?
Consider the following Python code using duck typing. What will it print?
Python
class Bird: def fly(self): return "Flying in the sky" class Airplane: def fly(self): return "Flying through clouds" def lets_fly(thing): return thing.fly() print(lets_fly(Bird()))
Attempts:
2 left
💡 Hint
Look at which class instance is passed to lets_fly function.
✗ Incorrect
The lets_fly function calls the fly method on the passed object. Since Bird instance is passed, it calls Bird.fly() which returns "Flying in the sky".
❓ Predict Output
intermediate2:00remaining
What happens when an object lacks the expected method?
What will be the output of this code?
Python
class Fish: def swim(self): return "Swimming in water" def lets_fly(thing): return thing.fly() print(lets_fly(Fish()))
Attempts:
2 left
💡 Hint
Check if Fish has a fly method.
✗ Incorrect
The lets_fly function calls fly() on the Fish instance, but Fish does not have a fly method, so Python raises AttributeError.
🧠 Conceptual
advanced1:30remaining
Which statement best describes duck typing?
Choose the best description of duck typing in Python.
Attempts:
2 left
💡 Hint
Think about how Python treats objects based on their behavior, not their type.
✗ Incorrect
Duck typing means you use an object based on whether it has the required methods or properties, not based on its class or type.
❓ Predict Output
advanced2:00remaining
What is the output of this duck typing with multiple objects?
What will this code print?
Python
class Dog: def speak(self): return "Woof!" class Cat: def speak(self): return "Meow!" def animal_sound(animal): return animal.speak() print(animal_sound(Dog())) print(animal_sound(Cat()))
Attempts:
2 left
💡 Hint
Check the order of print statements and which class instances are passed.
✗ Incorrect
animal_sound(Dog()) returns "Woof!" and animal_sound(Cat()) returns "Meow!". They print in that order separated by newline.
🔧 Debug
expert2:30remaining
Why does this duck typing code raise an error?
This code is intended to use duck typing but raises an error. What is the cause?
Python
class Car: def drive(self): return "Driving fast" def lets_drive(vehicle): return vehicle.drive() print(lets_drive("fast car"))
Attempts:
2 left
💡 Hint
Check if the string "fast car" has a drive method.
✗ Incorrect
The string "fast car" does not have a drive method, so calling vehicle.drive() raises AttributeError.