Sub topic 2
How Python finds an attribute or method
This chapter assumes you can define classes, create instances, and use self. You should also be comfortable with f-strings and print.
When you write obj.something, Python has to decide where something lives. Every later topic in inheritance depends on this search, including overriding, super(), and multiple inheritance.
The lookup order
For a plain attribute read such as d.legs, Python searches in this order and stops at the first match:
- The instance's own attributes, stored in
d.__dict__. - The instance's class.
- Each parent class of that class, from the nearest parent to the farthest.
object, the root of every class.
If nothing matches, Python raises AttributeError.
Watching the search happen
Methods and class attributes are stored once, on the class that defines them. Instances do not get copies.
class Animal:
legs = 4
def __init__(self, name):
self.name = name
def speak(self):
return f"{self.name} makes a sound"
class Dog(Animal):
def fetch(self):
return f"{self.name} fetches"
d = Dog("Rex")
print(d.speak()) # Rex makes a sound
print("name" in vars(d)) # True: stored on the instance
print("legs" in vars(d)) # False
print("legs" in vars(Animal)) # True: stored on the parent class
print("speak" in vars(Dog)) # False: Dog does not define it
print("speak" in vars(Animal)) # Trued.speak() works even though Dog has no speak. Python checks d, then Dog, then finds speak in Animal. The method is called with d as self, so self.name still reads from the instance.
Shadowing: the nearest match wins
Because the search stops at the first match, a name found earlier hides the same name found later. Assigning through an instance always writes to that instance's __dict__, never to the class.
class Animal:
legs = 4
class Dog(Animal):
pass
d = Dog()
d.legs = 3 # creates an instance attribute
print(d.legs) # 3
print(Animal.legs) # 4, unchanged
del d.legs # remove the instance attribute
print(d.legs) # 4, found on Animal againMethod overriding uses the same rule. A method defined on Dog is found before one with the same name on Animal, so the subclass version runs. The next chapter builds on this.
Common errors
- Expecting an assignment to change the parent.
d.legs = 3shadows the class value fordonly. To change it for every instance, assign on the class:Animal.legs = 3. - Misreading an AttributeError. The message names the instance's class, such as
'Dog' object has no attribute 'wings'. The name was missing everywhere on the search path, not only onDog. - Setting attributes on the wrong object. Assigning
self.xinside a method creates an attribute on the instance. Writingx = 1in the class body creates a class attribute shared by all instances.
Where the "parents in order" comes from
Step 3 says "each parent class, nearest first." With one parent this order is obvious. With several parents, Python needs a fixed order. It stores that order on the class as __mro__, which a later chapter covers. For now you can print it:
class Animal:
pass
class Dog(Animal):
pass
print([c.__name__ for c in Dog.__mro__]) # ['Dog', 'Animal', 'object']The classes in that list are the ones searched, left to right, after the instance itself.
Exercise
Given the classes below, what does the last line print, and where does Python find each name it uses? class Base: label = "base" def show(self): return self.label class Child(Base): pass c = Child() c.label = "mine" print(c.show(), Child.label)
Show answer
It prints "mine base". Python finds show on Base, because neither c nor Child defines it. Inside show, self is c, so self.label is found first in c's own _dict_ and returns "mine". Child.label is a lookup on the class, so it skips the instance and finds "base" on Base.