liveBook · Manning

Attribute lookup

As explained in Python Workout: 50 ten-minute exercises

Attribute lookup is the runtime process Python uses to resolve a named attribute accessed through an object.

When Python evaluates a.b, it follows a defined search path rather than the LEGB rule used for variables. The path is ICPO: instance, class, parents, and object. section 9.10

The lookup proceeds in this order:

  • Check the instance a for an attribute named b; return it if found. section 9.10
  • If the instance lacks b, check type(a), the object's class. section 9.10
  • Continue through parent classes and object when the earlier searches do not provide the attribute. section 9.10

Methods found on a class

For s = 'abcd', s.upper() first checks the string instance, then str.upper. Finding upper on str retrieves the method and invokes it through s. Similarly, an instance of Bar can call x2 from Foo and x3 from Bar.

How Python Workout: 50 ten-minute exercises covers it

How deep it goes
Explains the ICPO search order and method retrieval, while stopping before detailed descriptor or invocation internals.
Examples
Uses string.upper, Foo and Bar method calls, and inheritance diagrams to illustrate lookup across instances, classes, and parents.
What it assumes
Assumes familiarity with Python variables, objects, classes, instances, and the LEGB rule for variable lookup.
What you can do after
Evaluate why an instance method call succeeds when the method is defined on its class or an inherited parent.
How it connects
Connects attribute lookup with variables, LEGB, classes, instances, methods, inheritance, and object.

Also explained in

Compare how 2 books explain attribute lookup →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Workout: 50 ten-minute exercises. The section links point to the parts of the book it draws on.