PCPP 32 10x PCPP Certified Professional Python Programmer 1 · Free Practice Question Medium
Question 22
You are designing a set of classes to model a game where different characters can possess multiple abilities like swimming, flying, and running. You need to decide between using single or multiple inheritance and composition to model these abilities effectively. Consider the following code:
- class Swimmer:
- def swim(self):
- return "Swimming"
- class Flyer:
- def fly(self):
- return "Flying"
- class Runner:
- def run(self):
- return "Running"
- class SuperHero(Swimmer, Flyer, Runner):
- def super_powers(self):
- return f"{self.swim()}, {self.fly()}, {self.run()}"
Which of the following statements correctly describes the design and behavior of the SuperHero class?
-
A
The
SuperHeroclass demonstrates composition because it has methods that delegate to instances of other classes. -
B
The
super_powersmethod in theSuperHeroclass will fail because of a method resolution order (MRO) conflict between the parent classes. -
C
The
SuperHeroclass uses single inheritance by inheriting fromSwimmeronly. -
D
The
SuperHeroclass uses multiple inheritance and can access methods from all its parent classes.
Reveal correct answer
Correct answer: D
A.
This statement is incorrect because composition would involve the SuperHero class having instances of Swimmer, Flyer, and Runner as attributes and delegating the respective methods to those instances. Here, SuperHero directly inherits the methods.
B.
This statement is incorrect because there is no method resolution order (MRO) conflict in this scenario. The MRO is handled by Python’s C3 linearization algorithm, which ensures a well-defined order in which methods are resolved. The super_powers method will work correctly.
C.
This statement is incorrect because the SuperHero class uses multiple inheritance, inheriting from Swimmer, Flyer, and Runner, not just Swimmer.
D.
The SuperHero class indeed uses multiple inheritance. It can access the swim method from Swimmer, the fly method from Flyer, and the run method from Runner.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
