Sobes.tech
Junior — Middle

What happens if you try to access a class attribute that was not declared or defined?

sobes.tech AI

Answer from AI

If you try to access a class attribute in Python that has not been declared or defined, an AttributeError exception will be raised. This happens because the interpreter cannot find the specified attribute either in the object itself or in its classes.

Example:

class MyClass:
    pass

obj = MyClass()
print(obj.some_attribute)  # AttributeError: 'MyClass' object has no attribute 'some_attribute'

To avoid this error, you can use the getattr function with a default value:

value = getattr(obj, 'some_attribute', None)  # returns None if the attribute is missing