Inheritance Searches Namespace Trees
The whole point of a namespace tool like the class
statement is to support name
inheritance. In Python,
inheritance happens when an object is qualified, and involves
searching an attribute definition tree (one or more namespaces).
Every time you use an expression of the form
object.attr
where object is an instance or class
object, Python searches the namespace tree at and above
object
, for the first attr
it
can find. Because lower definitions in the tree override higher ones,
inheritance forms the basis of specialization.
Attribute Tree Construction
Figure 6.4 sketches the way namespace trees are constructed. In general:
Instance attributes are generated by assignments to
self
attributes in methods.Class attributes are created by statements (assignments) in
class
statements.Superclass links are made by listing classes in parentheses in a
class
statement header.
The net result is a tree of attribute namespaces, which grows from an instance, to the class it was generated from, to all the superclasses listed in the class headers. Python searches upward in this tree from instances to superclasses, each time you use qualification to fetch an attribute name from an instance object.[46]
Figure 6-4. Namespaces tree construction and inheritance
Specializing Inherited Methods
The tree-searching model of inheritance we just described turns out to be a great ...
Get Learning Python now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.