At a loss on python scoping.
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Tue Mar 26 08:43:29 EDT 2013
On Tue, 26 Mar 2013 14:19:21 +0800, Shiyao Ma wrote:
> PS, I now python's scoping rule is lexical rule (aka static rule). How
> does LEGB apply to class?
It doesn't. Python does not use the same lookup rules for attributes and
unqualified names.
Attribute lookups follow inheritance rules. `instance.name` searches in
this order, from first to last:
if it exists, call instance.__class__.__getattribute__(name);
look in the instance __dict__;
look in the class __dict__;
for each superclass in the inheritance chain:
look in the superclass __dict__;
if it exists, call instance.__class__.__getattr__(name)
(the above is a little simplified, but is close enough for ordinary work).
Unqualified `name` follow this lookup rule:
if name is recognised by the compiler as a local name:
look in the local function namespace;
otherwise:
look in any enclosing function scopes;
look in the global scope;
look in the builtins.
--
Steven
More information about the Python-list
mailing list