Sobes.tech
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:

  1. It first looks for the attribute attr in the instance some itself (in its __dict__).
  2. If the attribute is not found, the search continues in the class to which some belongs, and then along the inheritance chain.
  3. If the attribute is found and it is, for example, a method, it will be called or returned as an object.
  4. If the attribute is absent, an AttributeError exception 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'
What will happen when executing the command… - sobes.tech