copy from
Namespaces: The Whole Story
Now that we’ve examined class and instance objects, the Python namespace story is
complete. For reference, I’ll quickly summarize all the rules used to resolve names
here. The first things you need to remember are that qualified and unqualified names
are treated differently, and that some scopes serve to initialize object namespaces:
• Unqualified names (e.g., X) deal with scopes.
• Qualified attribute names (e.g., object.X) use object namespaces.
• Some scopes initialize object namespaces (for modules and classes).
Simple Names: Global Unless Assigned
Unqualified simple names follow the LEGB lexical scoping rule outlined for functions
in Chapter 16:
Assignment (X= value)
Makes names local: creates or changes the name X in the current local scope,
unless declared global.
Reference (X)
Looks for the name X in the current local scope, then any and all enclosing functions,
then the current global scope, then the built-in scope.
Attribute Names: Object Namespaces
Qualified attribute names refer to attributes of specific objects, and obey the rules for
modules and classes. For class and instance objects, the reference rules are augmented
to include the inheritance search procedure:
Assignment (object.X= value)
Creates or alters the attribute name X in the namespace of the object being qualified,
and none other. Inheritance-tree climbing happens only on attribute
reference, not on attribute assignment.
Reference (object.X)
For class-based objects, searches for the attribute name X in object, then in all
accessible classes above it, using the inheritance search procedure. For nonclass
objects such as modules, fetches X from object directly.