PCAP 31 03 PCAP Certified Associate Python Programmer · Free Practice Question Hard
Question 4
Q690 - OOP
Which of the following classes contain a usable constructor?
(Select two answers.)
-
A
- class Upper:
- def __init__(self):
- return False
-
B
- class Middle:
- def __init__():
- self.color = None
-
C
- class Working:
- def __init__(self):
- raise KeyError
-
D
- class Lower:
- def __init__(self):
- self.color = "blue"
Reveal correct answers
Correct answers: C, D
Explanation
Topics: class __init__() self KeyError
Try it yourself:
- class Lower:
- def __init__(self):
- self.color = "blue"
- print(Lower().color) # blue
- class Working:
- def __init__(self):
- raise KeyError
- working = Working() # KeyError
- class Middle:
- def __init__():
- self.color = None
- # middle = Middle()
- # TypeError: __init__() takes 0 positional
- # arguments but 1 was given
- class Upper:
- def __init__(self):
- return False
- # upper = Upper()
- # TypeError: __init__() should return None, not 'bool'
Explanation:
A constructor is allowed to raise an exception.
A constructor needs the object reference self as a parameter.
A constructor cannot return a value.
Q690 (Please refer to this number, if you want to write me about this question.)
A.
This choice does not contain a usable constructor because it defines the __init__ method with a return statement that returns a boolean value. Constructors in Python should initialize the object's state, not return values. This implementation does not follow the standard constructor format.
B.
This choice does not contain a usable constructor because the __init__ method is missing the self parameter. In Python, the self parameter is necessary to reference the instance of the class, so this constructor would not work as intended.
C.
This choice also contains a usable constructor, despite raising a KeyError exception within it. The presence of the __init__ method with the self parameter makes it a valid constructor. While raising an exception may not be common practice, it still fulfills the requirement of initializing the object.
D.
This choice contains a usable constructor because it defines the __init__ method with the self parameter, which is the standard way to define a constructor in Python classes. It initializes an instance variable color with the value "blue".
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
