Overriding parent class methods #
Child classes can override methods inherited from the parent class by redefining them with the same name. This allows child classes to modify the behavior of the inherited method to suit their specific needs.
Let's take a look at an example from the previous lesson:
class Animal:
alive = True
def __init__(self, name):
self.name = name
def eat(self):
print(f"The animal {self.name} is eating")
class Dog(Animal):
def eat(self):
print(f"The dog named {self.name} is eating")
In the example above, the Dog class has its own eat() method. And when we call this method from Dog objects, it will call the eat() method from the Dog class instead of the Animal class.
bird = Animal("Bird")
dog = Dog("Clark")
bird.eat() # The animal Bird is eating
dog.eat() # The dog named Clark is eating
Exercise #
- Define the
__str__method in ourMyUpperStrclass to return the text in all uppercase instead of the original text value. You can use theupper()method for this challenge.
Tests #
print(MyStr("Python is awesome!"))should print the message"Python is awesome!"print(MyUpperStr("Python is awesome!"))should print the message"PYTHON IS AWESOME!"
Getting Started with Python
Data Types
Python Functions
Statements in Python
Basic Debugging in Python
Basic Algorithm
Object-Oriented Programming
Error Handling
Intermediate Algorithm
Python Modules