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
  • B
  • C
  • D
Reveal correct answers

Correct answers: C, D

Explanation

Topics: class __init__() self KeyError


Try it yourself:


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.

You must be logged in to post a comment.

Preparing For

Your Certification?

255+ certifications
Detailed explanations
Free PDF samples

Has All The Questions You Need