Bird
Raised Fist0
Pythonprogramming~10 mins

Polymorphism through functions in Python - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

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
Concept Flow - Polymorphism through functions
Define function with parameter obj
Call method on obj
Python finds method in obj's class
Execute method specific to obj's class
Return result
Function output varies by obj type
The function calls a method on any object passed in. Python runs the version of the method that belongs to the object's class, allowing different behaviors.
Execution Sample
Python
class Dog:
    def speak(self):
        return "Woof!"

def animal_sound(animal):
    return animal.speak()

print(animal_sound(Dog()))
This code defines a Dog class with a speak method and a function that calls speak on any animal object.
Execution Table
StepActionEvaluationResult
1Define class Dog with method speakNo outputDog class ready
2Define function animal_sound with parameter animalNo outputFunction ready
3Call animal_sound with Dog instanceanimal = Dog()Dog object created
4Inside animal_sound, call animal.speak()Calls Dog.speak()"Woof!" returned
5animal_sound returns "Woof!"Return value "Woof!""Woof!" printed
6Program endsNo more codeExecution stops
💡 Program ends after printing the dog's sound
Variable Tracker
VariableStartAfter Step 3After Step 4Final
animalundefinedDog instanceDog instanceDog instance
return valueundefinedundefined"Woof!""Woof!"
Key Moments - 2 Insights
Why does animal.speak() call Dog's speak method and not some other method?
Because animal is a Dog instance at step 4, Python looks up speak in Dog's class and runs that method, as shown in execution_table row 4.
What if we pass a different animal with a different speak method?
The function calls that object's speak method instead, showing polymorphism. The function doesn't care about the type, only that speak exists.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 4, what method is called?
Aprint()
BDog.speak()
Canimal_sound()
DNone
💡 Hint
Check the 'Evaluation' column at step 4 in execution_table
At which step does the function return the string "Woof!"?
AStep 3
BStep 4
CStep 5
DStep 6
💡 Hint
Look at the 'Result' column for step 5 in execution_table
If we pass an object without a speak method, what will happen during execution?
APython raises an AttributeError at step 4
BThe function returns None
CThe function prints nothing
DThe program ends normally
💡 Hint
Recall that at step 4, animal.speak() is called; if speak doesn't exist, Python errors
Concept Snapshot
Polymorphism through functions:
- Define a function that calls a method on its parameter.
- Pass different objects with that method.
- Python runs the method of the object's class.
- Function behavior changes based on object type.
- No need to check object type explicitly.
Full Transcript
This example shows polymorphism through functions in Python. We define a Dog class with a speak method. Then we define a function animal_sound that calls speak on any object passed in. When we call animal_sound with a Dog instance, Python runs Dog's speak method and returns "Woof!". The execution table traces each step: defining classes and functions, creating objects, calling methods, and returning results. The variable tracker shows how the variable animal holds the Dog instance and how the return value changes. Key moments clarify why the correct method is called and what happens if a different object is passed. The quiz tests understanding of method calls, return steps, and error cases. This teaches how functions can work with different objects sharing the same method name, a core idea of polymorphism.

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

  1. Step 1: Understand polymorphism concept

    Polymorphism means one function can handle different types of inputs.
  2. Step 2: Relate to function behavior

    In Python, a single function can accept various data types and behave accordingly.
  3. Final Answer:

    A single function works with different data types -> Option D
  4. 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

  1. Step 1: Recall Python type checking methods

    Using isinstance() is the recommended way to check type in Python.
  2. Step 2: Compare options

    if isinstance(value, int): uses isinstance(value, int), which correctly checks if value is an int or subclass.
  3. Final Answer:

    if isinstance(value, int): -> Option C
  4. 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
  • Not checking type at all
3.

What is the output of this code?

def describe(value):
    if isinstance(value, int):
        return f"Integer: {value}"
    elif isinstance(value, str):
        return f"String: {value}"
    else:
        return "Unknown type"

print(describe(10))
print(describe('hello'))
print(describe(3.14))
medium
A. Integer: 10\nString: hello\nUnknown type
B. Integer: 10\nString: hello\nFloat: 3.14
C. Unknown type\nUnknown type\nUnknown type
D. Integer: 10\nUnknown type\nUnknown type

Solution

  1. Step 1: Check input 10

    10 is int, so returns 'Integer: 10'.
  2. Step 2: Check input 'hello'

    'hello' is str, so returns 'String: hello'.
  3. Step 3: Check input 3.14

    3.14 is float, not int or str, so returns 'Unknown type'.
  4. Final Answer:

    Integer: 10 String: hello Unknown type -> Option A
  5. 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

  1. Step 1: Analyze input 'abc'

    String input returns 'abcabc' by concatenation, no error.
  2. Step 2: Analyze input [1, 2, 3]

    List input goes to else: value / 2, but dividing list by 2 causes TypeError.
  3. Step 3: Fix the error

    Need to add a check for list type or avoid dividing list by 2.
  4. Final Answer:

    Error: Cannot divide list by 2; fix by handling list separately -> Option B
  5. 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

  1. Step 1: Check first call combine('Hi, ', 'there!')

    Both are strings, so returns concatenation 'Hi, there!'.
  2. Step 2: Check second call combine([1, 2], [3, 4])

    Both are lists, so returns concatenated list [1, 2, 3, 4].
  3. Step 3: Check third call combine('Hello', [1, 2])

    Types differ, so returns None.
  4. Final Answer:

    'Hi, there!' [1, 2, 3, 4] None -> Option A
  5. Quick Check:

    Type checks control output [OK]
Hint: Check types of both inputs before combining [OK]
Common Mistakes:
  • Not checking both inputs' types
  • Trying to combine different types directly
  • Returning wrong default for mismatched types