Bird Flying with Polymorphism

Create a class Bird with a method fly(). Implement child classes Sparrow and Ostrich that override the fly() method, where the Ostrich class should print a message that it cannot fly.

Example 1:

Input: Sparrow 
Output: "Sparrow is flying"

Example 2:

Input: Ostrich
Output: "Ostrich cannot fly"

Override the fly() method in each subclass to return the respective flying behavior.

class Bird:
    def fly(self):

class Sparrow(Bird):
    def fly(self):
        return "Sparrow is flying"

class Ostrich(Bird):
    def fly(self):
        return "Ostrich cannot fly"

# Test the classes
sparrow = Sparrow()
print(  # Output: Sparrow is flying

ostrich = Ostrich()
print(  # Output: Ostrich cannot fly

© Let’s Data Science


Unlock AI & Data Science treasures. Log in!