python: class attributes and instance attributes

Python’s class attributes and object attributes are stored in separate dictionaries. For the object f1, these can be accessed via, respectively, f1.__class__.__dict__ and f1.__dict__. Executing print f1.__class__ is Foo will output True.

When you reference the attribute of an object, Python first tries to look it up in the object dictionary. If it does not find it there, it checks the class dictionary (and so on up the inheritance heirarchy).

When you assign to f1.a, you are adding an entry to the object dictionary for f1. Subsequent lookups of f1.a will find that entry. Lookups of f2.a will still find the class attribute — the entry in the class attribute dictionary.

You can cause the value of f1.a to revert to 1 by deleting it:

del f1.a

This will remove the entry for a in the object dictionary of f1, and subsequent lookups will continue on to the class dictionary. So, afterwards, print f1.a will output 1.

Leave a Comment