Inheritance & polymorphism
Computer Science · Python
Question 1 of 10
0What does this Python code print? class A: def value(self): return 6 class B(A): pass print(B().value() + 8)
Decimals (0.75 or 0,75), fractions (3/4) and mixed numbers (1 1/2) are accepted. Do not use thousands separators.
How to type your answer
- Fractions: 3/4. Mixed numbers: 1 1/2.
- Decimals with a point or a comma: 0.75 or 0,75.
- Negative numbers start with a minus: -3/4.
- Percentages need the % sign: 75%.
Stuck? Read the explanation
Unlocks at a streak of 5 correct answers in a row.
Embed this practice on your site or class page
Paste this HTML into your page. Students practise right there; it is free and needs no account.
Inheritance & polymorphism explained
Inheritance lets a new class reuse and extend an existing class, and polymorphism lets code call the same method name on different classes and get the behaviour of each object's own class. Together they reduce repetition and let you add new types without rewriting the code that uses them.
A subclass is defined by putting the parent class, or superclass, in parentheses, as in class Dog(Animal). The subclass inherits the parent's attributes and methods. It can override a method by defining one with the same name, and it can call the parent's version with super(). Python decides which method to run from the actual object at run time, so a loop over mixed animals calls each object's own speak method.
class Animal:
def speak(self):
return "..."
class Dog(Animal):
def speak(self):
return "Woof"
class Cat(Animal):
def speak(self):
return "Meow"
for pet in [Dog(), Cat(), Animal()]:
print(pet.speak())
Worked example
Trace the loop above.
- The first object is a Dog, which overrides speak, so pet.speak() returns "Woof".
- The Cat overrides speak and returns "Meow".
- The Animal object has no override, so it returns "...".
- The output is three lines: Woof, Meow and then "...".
What you will practise
New numbers every time you practise. Levels: Easy, Medium, Hard. Each answer is followed by a worked explanation.
Example questions
Easy
What does this Python code print? class A: def value(self): return 4 class B(A): pass print(B().value() + 3)
Medium
What does this Python code print? class A: def value(self): return 5 class B(A): def value(self): return super().value() + 7 print(A().value() + B().value())
Hard
What does this Python code print? class Shape: def init(self, sides): self.sides = sides def area(self): return self.sides * 2 class Square(Shape): def init(self, n): super().init(4) self.size = n def area(self): return self.size * self.size shapes = [Square(5), Shape(4), Square(5), Square(7)] total = 0 for s in shapes: total += s.sides print(total)