Junior — Middle
What will happen when executing the command print(some.attr) if some is an instance of a class?
sobes.tech AI
Answer from AI
When executing the command print(some.attr), where some is an instance of a class, Python attempts to access the attribute attr of this object. The process is as follows:
- It first looks for the attribute
attrin the instancesomeitself (in its__dict__). - If the attribute is not found, the search continues in the class to which
somebelongs, and then along the inheritance chain. - If the attribute is found and it is, for example, a method, it will be called or returned as an object.
- If the attribute is absent, an
AttributeErrorexception will be raised.
Example:
class MyClass:
def __init__(self):
self.attr = 'Attribute value'
some = MyClass()
print(some.attr) # Outputs: Attribute value
If attr is not defined, for example print(some.nonexistent), an error will occur:
AttributeError: 'MyClass' object has no attribute 'nonexistent'