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
Polymorphism through functions
📖 Scenario: Imagine you are creating a simple program that can greet different types of people or animals. Each type has its own way of greeting, but you want to use the same function name to say hello. This is called polymorphism, where one function name works differently depending on the input.
🎯 Goal: You will build a program that defines different greeting functions for a Person and a Dog. Then you will write a single function called greet that calls the correct greeting based on the input. Finally, you will test the greet function with both a person and a dog.
📋 What You'll Learn
Create two classes: Person and Dog with their own greeting methods
Create a function called greet that takes one argument and calls the correct greeting method
Test the greet function with a Person instance and a Dog instance
Print the greetings to see the different outputs
💡 Why This Matters
🌍 Real World
Polymorphism helps programmers write flexible code that can work with different types of objects without changing the function names. For example, a messaging app might use polymorphism to send messages to different devices like phones, tablets, or computers using the same function name.
💼 Career
Understanding polymorphism is important for software developers because it allows writing cleaner, reusable, and easier-to-maintain code. It is a key concept in object-oriented programming used in many programming jobs.
Progress0 / 4 steps
1
Create Person and Dog classes with greeting methods
Create a class called Person with a method say_hello that returns the string "Hello, I am a person.". Also create a class called Dog with a method say_hello that returns the string "Woof! I am a dog.".
Python
Hint
Remember to use def say_hello(self): inside each class and return the exact greeting strings.
2
Create the greet function
Create a function called greet that takes one parameter called entity. Inside the function, call the say_hello method of entity and return its result.
Python
Hint
Use entity.say_hello() to call the method on the passed object.
3
Create instances of Person and Dog
Create a variable called person and assign it an instance of the Person class. Create another variable called dog and assign it an instance of the Dog class.
Python
Hint
Use person = Person() and dog = Dog() to create the objects.
4
Print greetings using the greet function
Use the print function to display the result of calling greet(person) and then greet(dog).
Python
Hint
Use print(greet(person)) and print(greet(dog)) to show the greetings.
Practice
(1/5)
1.
What does polymorphism through functions mean in Python?
easy
A. Functions cannot be reused with different inputs
B. Multiple functions have the same name but different parameters
C. Functions can only accept one specific data type
D. A single function works with different data types
Solution
Step 1: Understand polymorphism concept
Polymorphism means one function can handle different types of inputs.
Step 2: Relate to function behavior
In Python, a single function can accept various data types and behave accordingly.
Final Answer:
A single function works with different data types -> Option D
Quick Check:
Polymorphism = single function, many types [OK]
Hint: Think: one function, many input types [OK]
Common Mistakes:
Confusing polymorphism with function overloading
Believing functions accept only one data type
Mixing polymorphism with inheritance
2.
Which of the following is the correct way to check a variable's type inside a function for polymorphism?
def process(value):
# What to use here?
pass
easy
A. if type(value) == int:
B. if value is int:
C. if isinstance(value, int):
D. if value == int:
Solution
Step 1: Recall Python type checking methods
Using isinstance() is the recommended way to check type in Python.
Step 2: Compare options
if isinstance(value, int): uses isinstance(value, int), which correctly checks if value is an int or subclass.
Final Answer:
if isinstance(value, int): -> Option C
Quick Check:
Use isinstance() for type checks [OK]
Hint: Use isinstance() to check types safely [OK]
Common Mistakes:
Using 'type() == int' which fails with subclasses
Using 'is' or '==' incorrectly for type comparison
3.14 is float, not int or str, so returns 'Unknown type'.
Final Answer:
Integer: 10
String: hello
Unknown type -> Option A
Quick Check:
Type checks match outputs [OK]
Hint: Match isinstance checks to output lines [OK]
Common Mistakes:
Assuming float is handled like int or str
Ignoring else case output
Mixing output order
4.
Find the error in this polymorphic function and fix it:
def process(value):
if isinstance(value, int):
return value * 2
elif isinstance(value, str):
return value + value
else:
return value / 2
print(process('abc'))
print(process([1, 2, 3]))
medium
A. No error; code runs fine
B. Error: Cannot divide list by 2; fix by handling list separately
C. Error: Missing return statement for int type
D. Error: Cannot multiply string by 2; fix by converting to int
Solution
Step 1: Analyze input 'abc'
String input returns 'abcabc' by concatenation, no error.
Step 2: Analyze input [1, 2, 3]
List input goes to else: value / 2, but dividing list by 2 causes TypeError.
Step 3: Fix the error
Need to add a check for list type or avoid dividing list by 2.
Final Answer:
Error: Cannot divide list by 2; fix by handling list separately -> Option B
Quick Check:
List / 2 causes error [OK]
Hint: Check operations valid for each type [OK]
Common Mistakes:
Assuming all types support division
Not testing with different input types
Ignoring TypeError exceptions
5.
Write a polymorphic function combine that accepts either two strings or two lists and returns their concatenation. What is the output of this code?
def combine(a, b):
if isinstance(a, str) and isinstance(b, str):
return a + b
elif isinstance(a, list) and isinstance(b, list):
return a + b
else:
return None
print(combine('Hi, ', 'there!'))
print(combine([1, 2], [3, 4]))
print(combine('Hello', [1, 2]))
hard
A. 'Hi, there!'\n[1, 2, 3, 4]\nNone
B. 'Hi, there!'\n[1, 2]\n[3, 4]
C. None\nNone\nNone
D. 'Hi, there!'\nNone\nNone
Solution
Step 1: Check first call combine('Hi, ', 'there!')
Both are strings, so returns concatenation 'Hi, there!'.
Step 2: Check second call combine([1, 2], [3, 4])
Both are lists, so returns concatenated list [1, 2, 3, 4].
Step 3: Check third call combine('Hello', [1, 2])
Types differ, so returns None.
Final Answer:
'Hi, there!'
[1, 2, 3, 4]
None -> Option A
Quick Check:
Type checks control output [OK]
Hint: Check types of both inputs before combining [OK]