PCAP 31 03 PCAP Certified Associate Python Programmer · Free Practice Question Medium
Question 53
Q194 - OOP
What is the expected behavior of the following snippet?
- class Team:
- def show_ID(self):
- print(self.get_ID())
- def get_ID(self):
- return "anonymous"
- class A(Team):
- def get_ID(self):
- return "Alpha"
- a = A()
- a.show_ID()
-
A
It outputs an empty line.
-
B
It raises an exception.
-
C
It outputs
anonymous -
D
It outputs
Alpha
Reveal correct answer
Correct answer: D
Explanation
Topics: class inheritance object methods self
Try it yourself:
- class Team:
- def show_ID(self):
- print(self.get_ID())
- def get_ID(self):
- return "anonymous"
- class A(Team):
- def get_ID(self):
- return "Alpha"
- a = A()
- a.show_ID() # Alpha
Explanation:
Class A will override the get_ID() method of its superclass Team
and therefore the output will be Alpha
Q194 (Please refer to this number, if you want to write me about this question.)
A. This choice is incorrect because the expected behavior of the snippet is not to output an empty line. The show_ID method prints the result of calling the get_ID method, which returns "Alpha" in this case, so the output will not be an empty line.
B. This choice is incorrect because the expected behavior of the snippet is not to raise an exception. The code is structured in a way that allows for method overriding, and the method calls are valid, so there should be no exceptions thrown during the execution of the snippet.
C. This choice is incorrect because the expected behavior of the snippet is to output "Alpha" due to the method overriding in class A. The get_ID method in class A is called when show_ID is invoked on an instance of class A, not the get_ID method in the Team class.
D. The expected behavior is that the snippet will output "Alpha" because the get_ID method in class A overrides the get_ID method in the Team class. When show_ID is called on an instance of class A, it will use the get_ID method defined in class A, which returns "Alpha".
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
