Sub topic 2
How Python Finds an Attribute or Method
This chapter assumes you can define classes, create instances, use self, and read simple f-strings. You should also know what a subclass is. Here you will learn the exact search Python runs when you write obj.name. That search explains inheritance, shadowing, and several common bugs.
One expression, an ordered search
Inheritance is not copying. When Dog inherits from Animal, Python does not copy Animal's attributes into Dog or into its instances. Each object and class keeps only its own names. When you write obj.name, Python looks for name in a fixed order and stops at the first match.
For ordinary attributes and methods, the order is:
- The instance's own
__dict__. - The instance's class, then each parent class, in order, up to
object. - If nothing matched,
AttributeError.
The order of classes in step 2 is called the method resolution order (MRO). With single inheritance it is the chain from child to parent to grandparent, ending at object. Multiple inheritance changes how this list is built. A later chapter covers that. Here, read "the MRO" as "the chain of parents".
Watching the lookup happen
Every instance and class stores its own names in a dictionary, which you can read with vars(). The helper below repeats the search by hand. It reports which object supplies a name.
class Animal:
legs = 4
def speak(self):
return "..."
class Dog(Animal):
sound = "woof"
def __init__(self, name):
self.name = name
def where(obj, name):
if name in vars(obj):
return "instance"
for klass in type(obj).__mro__:
if name in vars(klass):
return klass.__name__
return None
d = Dog("Rex")
print(where(d, "name")) # instance
print(where(d, "sound")) # Dog
print(where(d, "legs")) # Animal
print(where(d, "speak")) # Animal
print(where(d, "__init__")) # Dog
print(where(d, "__eq__")) # object
print(where(d, "tail")) # NoneThree things stand out:
nameis stored on the instance because__init__assigned it throughself.legsandspeakare stored once onAnimal. TheDoginstance reaches them by walking up the chain.__eq__comes fromobject. Every class ends atobject, so every instance already has methods such as__eq__,__repr__, and__str__.
The where helper simplifies things. It ignores descriptors (covered below) and classes that use __slots__, which have no instance __dict__.
Reading finds up the chain, writing stays local
Lookup walks upward, but assignment does not. obj.name = value stores the value in the instance's own __dict__. It never changes a class. This asymmetry causes most surprises with class attributes.
class Animal:
legs = 4
class Dog(Animal):
pass
d = Dog()
print(d.legs, Dog.legs, Animal.legs) # 4 4 4
d.legs = 3 # creates an instance attribute
print(d.legs, Dog.legs, Animal.legs) # 3 4 4
del d.legs # remove the instance attribute
Animal.legs = 6 # change the parent class
print(d.legs, Dog.legs, Animal.legs) # 6 6 6After d.legs = 3, the instance holds its own legs. It shadows (hides) the class value without changing it. After del d.legs, the search falls through to Animal again. Because lookup happens at access time, a change to Animal.legs is visible immediately through Dog and every instance that does not shadow it.
Two bugs this causes
Mutable class attributes are shared. self.dogs.append(...) does not assign to self. It finds the list on the class and changes it in place. Every instance sees the change.
class Kennel:
dogs = [] # one list, owned by the class
def add(self, name):
self.dogs.append(name)
a = Kennel()
b = Kennel()
a.add("Rex")
print(b.dogs) # ['Rex']If each instance needs its own list, create it in __init__ with self.dogs = [].
Augmented assignment reads from the class and writes to the instance. self.count += 1 means self.count = self.count + 1. The right side finds count on the class. The left side stores the result on the instance.
class Counter:
count = 0
def hit(self):
self.count += 1
c = Counter()
c.hit()
c.hit()
print(c.count, Counter.count) # 2 0The class value never changes. If you want a count shared by all instances, write Counter.count += 1. Inside a method, type(self).count += 1 does the same.
Where methods fit in
A method is a function stored in a class's __dict__. It is found by the same search as any other attribute. The difference appears at the moment of access. When the search finds a plain function on a class, Python wraps it in a bound method that remembers the instance. Calling the bound method passes that instance as self.
class Animal:
def speak(self):
return "..."
class Dog(Animal):
pass
d = Dog()
print(Dog.speak is Animal.speak) # True: one function, found on Animal
print(d.speak) # <bound method Animal.speak of <__main__.Dog object at 0x...>>
print(d.speak.__self__ is d) # True
print(d.speak.__func__ is Animal.speak) # True
print(d.speak() == Animal.speak(d)) # TrueThe line d.speak() is shorthand for "find speak on the class chain, bind it to d, call it". Dog.speak is Animal.speak is True because Dog has no speak of its own, so the search finds the one on Animal.
This is also what overriding means at the lookup level. When a subclass defines the same name, the search finds the subclass's version first and stops. The parent's version is still there, but it is not reached. The next chapter covers overriding in full.
Instance attributes can hide methods
The instance dictionary is checked before the class, so an instance attribute can hide a method of the same name.
class Animal:
def speak(self):
return "..."
a = Animal()
a.speak = lambda: "hi" # stored on the instance, so no binding happens
print(a.speak()) # hi
print(Animal().speak()) # ...The lambda takes no self argument. Python only binds functions that it finds on a class. A function stored on an instance is returned as it is. A common version of this bug is setting self.name = "x" in __init__ when the class also has a method called name. The method becomes unreachable on that instance.
Descriptors can change the order
The two-step search above covers most code. Some class attributes are descriptors, which are objects that define __get__ (and sometimes __set__). Functions are descriptors, and that is how binding works. property is another. A data descriptor, one that defines __set__, is checked before the instance dictionary and so cannot be shadowed.
The full order for obj.name is:
- A data descriptor found on the class chain, such as a
property. - The instance
__dict__. - A non-data descriptor or plain value found on the class chain. Plain functions fall here.
AttributeError.
class Account:
def __init__(self):
self._balance = 10
@property
def balance(self):
return self._balance
acct = Account()
print(acct.balance) # 10
try:
acct.balance = 99
except AttributeError as exc:
print("Blocked:", type(exc).__name__) # Blocked: AttributeError
acct.__dict__["balance"] = 99 # bypass assignment
print(acct.balance) # 10: the property still winsA property without a setter still counts as a data descriptor, which is why assignment fails and why the entry forced into __dict__ is ignored.
When nothing matches
If the search fails, Python raises AttributeError. Two tools are useful here:
getattr(obj, "name", default)returnsdefaultinstead of raising.hasattr(obj, "name")returnsTrueorFalse. It runs the full lookup, including inherited names and properties.
You can also hook into the failure. If the class defines __getattr__, Python calls it only after the normal search has failed. This is different from __getattribute__, which runs on every access and is rarely worth overriding.
class Dog:
def __init__(self):
self.name = "Rex"
def __getattr__(self, attr):
return f"<no {attr}>"
d = Dog()
print(d.name) # Rex: found normally, __getattr__ is not called
print(d.color) # <no color>: lookup failed, so __getattr__ ranBe careful with __getattr__. It turns every typo into a normal-looking value, which hides bugs.
Looking up on the class
Dog.legs runs a similar search, but it starts at Dog's own __dict__ and then walks up the parents. There is no instance in the way. You can also inspect the chain directly:
class Animal:
pass
class Dog(Animal):
pass
print([k.__name__ for k in Dog.__mro__]) # ['Dog', 'Animal', 'object']Quick reference
| Expression | What Python does |
|---|---|
| `obj.x` | Searches the instance, then the class chain. Descriptors may change the order. |
| `obj.x = v` | Stores `v` in the instance. A data descriptor, such as a `property`, intercepts this instead. |
| `del obj.x` | Removes `x` from the instance only. |
| `Cls.x` | Searches `Cls` and its parents. |
| `Cls.x = v` | Stores `v` on `Cls`. Subclasses and instances that do not shadow `x` see it. |
| `getattr(obj, "x", d)` | Runs the same search as `obj.x` and returns `d` on failure. |
| `vars(obj)` | Shows only the names stored on that one object. |
Debugging with the lookup in mind
When an attribute or method has an unexpected value, check these in order:
- Run
vars(obj)to see whether the instance shadows the name. - Run
type(obj).__mro__to see which classes are searched, and in what order. - Print
vars(klass)for each class in that order to find the first one defining the name. - Check whether the name is a
propertyor another descriptor.
Exercise
Given the code below, what do the three print calls output, and why? class Base: items = [] limit = 5 def add(self, x): self.items.append(x) self.limit += 1 class Child(Base): pass a = Child() b = Child() a.add("x") print(b.items) print(a.limit, b.limit) print(Base.limit)
Show answer
The calls print ['x'], then 6 5, then 5. Both instances share the single list stored on Base. The call self.items.append(x) finds it through the class and changes it in place, so b.items shows 'x'. The statement self.limit += 1 reads 5 from Base and stores 6 on the instance a. Instance b still finds 5 on Base, and Base.limit is never changed.
Exercise
A class Logger has a method level(self). In _init_ you write self.level = "INFO". After creating an instance, calling logger.level() raises TypeError. Explain the cause using the lookup order, and give one fix.
Show answer
The instance dictionary is searched before the class, so logger.level finds the string "INFO" stored on the instance and never reaches the method on the class. Calling a string raises TypeError. The fix is to give the attribute and the method different names, for example store self.level_name = "INFO" and keep the method level().