PCAP-31-03 practice question 7 of 25

Is it possible to safely check if a class object has a certain attribute0

Full set: 147 questions
Answer options
A: yes, by using the hasattr attribute
B: yes. by using the hasattr () method
C: yes, by using the hasattr () function Correct answer
D: no, it is not possible
Correct Answer:
C. yes, by using the hasattr () function
Explanation

The built-in function hasattr(obj, name) returns True when the supplied object possesses an attribute whose identifier is given by the second argument, and False otherwise. Because it is part of Python’s built-ins, it can be invoked on any object and constitutes the canonical, safe way to test for the presence of an attribute.

Why Incorrect

A. Describes “hasattr” as an attribute; it is a function, not an attribute.
B. Calls hasattr a method; it is a top-level built-in function, not bound to any class or object.
D. Python provides hasattr(); therefore the statement that no safe check exists is false.

References

1. Python Software Foundation, “Built-in Functions,” Python 3.12.3 docs, §4, hasattr() paragraph (https://docs.python.org/3/library/functions.html#hasattr).

2. MIT OpenCourseWare 6.0001, Lecture 8 Notes, slide “Testing Attributes with hasattr()”.

Scroll to Top