Duck Typing
Part of the Object Oriented Programming section of Coddy's Python journey — lesson 24 of 64.
Duck typing focuses on what an object can do, not what it is. If an object has the methods you need, you can use it - regardless of its class type.
Here are two unrelated classes with the same methods:
class Duck:
def swim(self):
return "Duck swimming"
def quack(self):
return "Quack!"
class Person:
def swim(self):
return "Person swimming"
def quack(self):
return "Person imitating a duck: Quack!"Notice that Duck and Person don't inherit from the same parent class, but they both have swim() and quack() methods.
Create a function that works with any "duck-like" object:
def make_it_swim_and_quack(duck_like_object):
print(duck_like_object.swim())
print(duck_like_object.quack())This function doesn't care about the object's type - it only cares that the object has the required methods.
Use the function with both classes:
make_it_swim_and_quack(Duck())
make_it_swim_and_quack(Person())Output:
Duck swimming
Quack!
Person swimming
Person imitating a duck: Quack!Add another "duck-like" class:
class Robot:
def swim(self):
return "Robot swimming with propellers"
def quack(self):
return "Robot sound: BEEP BEEP!"
make_it_swim_and_quack(Robot())Output:
Robot swimming with propellers
Robot sound: BEEP BEEP!Key Point: Duck typing allows polymorphism without inheritance. If an object has the methods you need, you can use it. This makes Python code flexible and follows the principle "it's easier to ask forgiveness than permission."
Challenge
MediumIn this challenge, you'll implement a system demonstrating duck typing with different file-like objects:
textfile.py: Implement theTextFileclass withread()andwrite(data)methodsdatabase.py: Implement theDatabaseclass with matching method signaturesnetworkresource.py: Implement theNetworkResourceclass with matching method signaturesdriver.py- Implement test cases that will verify your implementation works correctly
Each file contains detailed TODO comments guiding your implementation.
Cheat sheet
Duck typing focuses on what an object can do, not what it is. If an object has the methods you need, you can use it regardless of its class type.
Example of duck typing with unrelated classes that share the same methods:
class Duck:
def swim(self):
return "Duck swimming"
def quack(self):
return "Quack!"
class Person:
def swim(self):
return "Person swimming"
def quack(self):
return "Person imitating a duck: Quack!"Create a function that works with any "duck-like" object:
def make_it_swim_and_quack(duck_like_object):
print(duck_like_object.swim())
print(duck_like_object.quack())
# Works with any object that has swim() and quack() methods
make_it_swim_and_quack(Duck())
make_it_swim_and_quack(Person())Duck typing allows polymorphism without inheritance - if an object has the methods you need, you can use it. This makes Python code flexible and follows the principle "it's easier to ask forgiveness than permission."
Try it yourself
# TODO: Import the TextFile class from textfile.py
# TODO: Import the Database class from database.py
# TODO: Import the NetworkResource class from networkresource.py
def process_data(data_source, data):
# TODO: Call the read() method on data_source and print the result
# TODO: Call the write(data) method on data_source and print the result
pass
# Test with different data sources - DO NOT MODIFY THIS TEST CODE
text_file = TextFile()
database = Database()
network = NetworkResource()
print("Processing text file:")
process_data(text_file, "Hello, world!")
print("\
Processing database:")
process_data(database, "User record")
print("\
Processing network resource:")
process_data(network, "GET request")This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe self ParameterMethodsAttributesConstructor Method (__init__)Recap - Simple Calculator4Inheritance
Basic InheritanceThe super() FunctionMethod OverridingMultiple InheritanceMethod Resolution OrderRecap - Employee Hierarchy7Special Methods
Magic Methods IntroductionOperator OverloadingContainer Magic MethodsRecap - Custom List10Design Patterns Part 1
Intro to design patternSingleton PatternFactory PatternObserver PatternStrategy Pattern2Decorators
Introduction to DecoratorsProperty DecoratorStatic Method DecoratorClass Method Decorator5Polymorphism
Method Overriding RevisitedDuck TypingAbstract Classes and MethodsInterface DesignRecap - Shape Calculator8Advanced OOP Concepts
Composition vs InheritanceMixinsStatic and Class MethodsClass DecoratorsContext Managers3Class Properties
Instance vs Class VariablesProperty DecoratorsPrivate AttributesRecap - Bank Account Manager6Encapsulation
Public, Protected, Private MemAccess ModifiersInformation HidingProperty Decorators AdvancedRecap - Student Records System12Project: Library Management
Project OverviewBook and User Classes