Recall & Review
beginner
What is method overriding in Python?
Method overriding occurs when a subclass provides a specific implementation of a method that is already defined in its superclass. The subclass's method replaces the superclass's method when called on an instance of the subclass.Click to reveal answer
beginner
Why do we use method overriding?
We use method overriding to change or extend the behavior of a method inherited from a parent class, allowing subclasses to customize or improve functionality without changing the parent class.
Click to reveal answer
beginner
Example of method overriding in Python:<br><pre>class Animal:
def sound(self):
return "Some sound"
class Dog(Animal):
def sound(self):
return "Bark"</pre><br>What will <code>Dog().sound()</code> return?It will return "Bark" because the Dog class overrides the sound method of the Animal class with its own version.Click to reveal answer
intermediate
Can method overriding be used to call the parent class method as well?Yes. Inside the overriding method, you can call the parent class method using <code>super().method_name()</code> to reuse or extend the original behavior.Click to reveal answer
beginner
What happens if a subclass does not override a method from its superclass?If a subclass does not override a method, it inherits the method from the superclass and uses that implementation when the method is called.Click to reveal answer
What does method overriding allow a subclass to do?
✗ Incorrect
Method overriding lets a subclass provide its own version of a method that exists in the superclass.
How do you call the parent class method inside an overriding method?
✗ Incorrect
The
super() function is used to call the parent class method inside an overriding method.If a subclass does not override a method, what happens when the method is called on the subclass instance?
✗ Incorrect
The subclass inherits the method from the superclass and uses it if it does not override it.
Which of the following is NOT true about method overriding?
✗ Incorrect
Method overriding does NOT require changing the superclass code; it happens by defining a method with the same name in the subclass.
What will this code print?<br>
class A:
def greet(self):
return 'Hello from A'
class B(A):
def greet(self):
return 'Hello from B'
print(B().greet())✗ Incorrect
Class B overrides the greet method, so calling greet on B's instance returns 'Hello from B'.
Explain method overriding and why it is useful in object-oriented programming.
Think about how a child class can change a parent's method.
You got /4 concepts.
Describe how to call a parent class method from an overriding method in Python.
Use a built-in function to access the parent method.
You got /3 concepts.