PCAP 31 03 PCAP Certified Associate Python Programmer · Free Practice Question Hard
Question 8
Q595 - OOP
Given the code below,
which of the expressions will evaluate to True?
- class Alpha:
- def say(self):
- return "alpha"
- class Beta(Alpha):
- def say(self):
- return "beta"
- class Gamma(Alpha):
- def say(self):
- return "gamma"
- class Delta(Beta, Gamma):
- pass
- d = Delta()
- b = Beta()
(Select two answers.)
-
A
- b is d
-
B
- d.say() == "gamma"
-
C
- isinstance(d, Alpha)
-
D
- Gamma in Delta.__bases__
Reveal correct answers
Correct answers: C, D
Explanation
Topics: class multi inheritance class variables self
object methods MRO
Try it yourself/Explanation:
- class Alpha:
- def say(self):
- return "alpha"
- class Beta(Alpha):
- def say(self):
- return "beta"
- class Gamma(Alpha):
- def say(self):
- return "gamma"
- class Delta(Beta, Gamma):
- pass
- d = Delta()
- b = Beta()
- print(Gamma in Delta.__bases__) # True
- # Gamma is a direct superclass of Delta.
- print(isinstance(d, Alpha)) # True
- # d is an instance of Delta.
- # Alpha is a superclass of Delta.
- # Therefore d is also an instance of Alpha.
- print(b is d) # False
- # b and d are different objects
- # and even of different classes.
- print(d.say() == "gamma") # False
- print(d.say()) # beta
- # The topic here is Method Resolution Order (MRO)
- # In the inheritance list of the Delta class superclasses
- # Beta is first and therefore Delta will inherit
- # the say() method of the Beta class
- # which will return "Beta".
Q595 (Please refer to this number, if you want to write me about this question.)
A. The expression "b is d" will evaluate to False because b and d are instances of different classes (Beta and Delta, respectively), even though they both inherit from Alpha.
B. The expression "d.say() == 'gamma'" will evaluate to True because when the say() method is called on the object d of class Delta, it returns the string "gamma" as defined in the Gamma class, which is the last class in the method resolution order.
C. The expression "isinstance(d, Alpha)" will evaluate to True because the object d of class Delta is an instance of the class Alpha, as Delta inherits from both Beta and Gamma, which in turn inherit from Alpha.
D. The expression "Gamma in Delta.__bases__" will evaluate to True because the class Gamma is one of the base classes of the class Delta, as it inherits from both Beta and Gamma.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
