PCAP 31 03 PCAP Certified Associate Python Programmer · Free Practice Question Hard
Question 52
Q495 - OOP
Given the code below,
which of the expressions will evaluate to True?
- class Alpha:
- value = "Alpha"
- def say(self):
- return self.value.lower()
- class Beta(Alpha):
- value = "Beta"
- class Gamma(Alpha):
- def say(self):
- return self.value.upper()
- class Delta(Gamma, Beta):
- pass
- d = Delta()
- b = Beta()
(Select two answers.)
-
A
- d.value == "Alpha"
-
B
- Alpha in Delta.__bases__
-
C
- isinstance(d, Beta)
-
D
- d.say() == "BETA"
Reveal correct answers
Correct answers: C, D
Explanation
Topics: class class variables self object methods
Try it yourself/Explanation:
- class Alpha:
- value = "Alpha"
- def say(self):
- return self.value.lower()
- class Beta(Alpha):
- value = "Beta"
- class Gamma(Alpha):
- def say(self):
- return self.value.upper()
- class Delta(Gamma, Beta):
- pass
- d = Delta()
- b = Beta()
- print(isinstance(d, Beta)) # True
- # d is an instance of class Delta
- # and therefore an instance of its superclass Beta.
- print(d.say() == "BETA") # True
- print(d.say()) # BETA
- # Delta will inherit the say() method of the Gamma class
- # and the value attribute of the Beta class.
- # Therefore Delta's say() method will return "BETA"
- print(d.value == "Alpha") # False
- print(d.value) # Beta
- # The value attribute of the Alpha class
- # will be overridden by the value attribute of the Beta class.
- print(Alpha in Delta.__bases__) # False
- # The __bases__ attribute only lists the direct superclasses.
Q495 (Please refer to this number, if you want to write me about this question.)
A. The expression d.value == "Alpha" will evaluate to False because the value attribute in the Delta class is inherited from the Beta class, where it is set to "Beta". Therefore, the value attribute for the object d is "Beta", not "Alpha".
B.
The expression Alpha in Delta.__bases__ will evaluate to False because the class Alpha is not one of the direct base classes of the Delta class. In Python, the __bases__ attribute of a class contains a tuple of its direct base classes, and since Alpha is not a direct base class of Delta, the expression is False.
C. The expression isinstance(d, Beta) will evaluate to True because the object d is an instance of the class Beta, which is a subclass of Alpha. Since Delta inherits from both Gamma and Beta, it also inherits the properties of Beta, making d an instance of Beta as well.
D. The expression d.say() == "BETA" will evaluate to True because the say() method in the Delta class returns the uppercase value of the attribute 'value'. Since the value in the Delta class is "Beta", calling d.say() will return "BETA", which is equal to the comparison value.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
