0
0
Pythonprogramming~15 mins

Polymorphism through functions in Python - Mini Project: Build & Apply

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

Use print(greet(person)) and print(greet(dog)) to show the greetings.