PCAP 31 03 PCAP Certified Associate Python Programmer · Free Practice Question Easy
Question 17
Q573 - OOP
If the class constructor is declared in the following way:
- class Class:
- def __init__(self, val=0):
- pass
Which one of the assignments is invalid?
-
A
object_1 = Class() -
B
object_1 = Class(1) -
C
object_1 = Class(1, 2) -
D
object_1 = Class(None)
Reveal correct answer
Correct answer: C
Explanation
Topics: class def __init__() self pass
Try it yourself:
- class Class:
- def __init__(self, val=0):
- pass
- # object_1 = Class(1, 2) # TypeError ...
- object_1 = Class()
- object_1 = Class(1)
- object_1 = Class(None)
Explanation:
The __init__() function has the object reference self
and one other parameter which has a default value.
Therefore you can call it without a parameter
or with exactly one parameter.
And None is just another value like 1
Q573 (Please refer to this number, if you want to write me about this question.)
A.
The assignment object_1 = Class() is valid because it calls the class constructor __init__ with the default value of val (which is 0 if not provided). This assignment correctly initializes an object of the Class class.
B.
The assignment object_1 = Class(1) is valid because it provides a single argument (1) to the class constructor __init__, which matches the expected parameter val. This assignment correctly initializes an object of the Class class.
C.
The assignment object_1 = Class(1, 2) is invalid because the __init__ method in the class Class only accepts one argument (val). Providing two arguments (1 and 2) in the assignment is not valid.
D.
The assignment object_1 = Class(None) is valid because None is a valid argument that can be passed to the class constructor __init__. This assignment correctly initializes an object of the Class class.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
