PCPP 32 10x PCPP Certified Professional Python Programmer 1 · Free Practice Question Easy
Question 9
Suppose you have the following function:
- def my_function():
- """One-line description."""
- pass
How can you access the docstring using my_function object?
-
A
my_function.__class__ -
B
my_function.__str__ -
C
my_function.__repr__ -
D
my_function.__doc__
Reveal correct answer
Correct answer: D
A.
my_function.__class__, refers to the __class__ attribute, which returns the class to which an object belongs. It does not provide access to the docstring.
B.
my_function.__str__, refers to the __str__ method, which is used to provide a string representation of an object. It does not directly provide access to the docstring.
C.
my_function.__repr__, refers to the __repr__ method, which is used to provide a string representation that can be used to recreate the object. Like option B, it does not give direct access to the docstring.
D.
In Python, the docstring of a function can be accessed using the __doc__ attribute of the function object. The docstring is a string that provides a description of the function's purpose, usage, and any other relevant information. It is defined as a string literal that appears as the first statement in the function's body.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
