PCEP-30-02 practice question 16 of 35

What exception will be raised when you try to access an object attribute that is undefined?

Full set: 548 questions

Domain Functions and Exceptions

Answer options
A: NameError
B: SyntaxError
C: NotImplementedError
D: AttributeError Correct answer
E: ReferenceError
Correct Answer:
D. AttributeError
Explanation

An AttributeError is the specific exception raised in Python when an attempt to access or assign an attribute of an object fails because the attribute does not exist. This is a runtime error that occurs when the code is syntactically correct but refers to a member (e.g., a variable or method) that is not defined within the object's namespace. For example, if mylist is a list object, mylist.nonexistentmethod() would trigger an AttributeError.

Why Incorrect

A. NameError: Raised when a local or global variable name is not found in any scope, which is different from an attribute not being found within a specific object.
B. SyntaxError: Raised by the parser when it encounters code that violates Python's grammatical rules. It is a compile-time error, not a runtime attribute access error.
C. NotImplementedError: Intended to be raised from abstract methods in a base class to signal that a derived class must override the method.
E. ReferenceError: A rare exception raised when trying to access an attribute of a garbage-collected object via a weak reference proxy.

References

1. Python Software Foundation. "Built-in Exceptions — Python 3.11.5 documentation". Python.org. Retrieved October 2023. In the exception hierarchy documentation, AttributeError is defined as: "Raised when an attribute reference or assignment fails."

2. Lutz, Mark. Learning Python, 5th Edition. O'Reilly Media, 2013. Chapter 33, "Exception Basics," page 1038, distinguishes between NameError (undefined variable) and AttributeError (undefined attribute on an object).

3. Guttag, John V. "10. Classes and Object-Oriented Programming". Introduction to Computation and Programming Using Python, With Application to Understanding Data (2nd ed.). MIT Press, 2016, pp. 167-188. The chapter discusses the structure of objects and how accessing non-existent attributes leads to errors.

4. MIT OpenCourseWare. "Lecture 8: Object Oriented Programming". 6.0001 Introduction to Computer Science and Programming in Python, Fall 2016. The lecture notes and code examples demonstrate the creation of classes and instances, where attempting to access an undefined attribute on an instance would result in an AttributeError.

Scroll to Top