First understand what a namespace is, a namespace is a "named-and-object" mapping, implemented in Python with Dict.
The scope, however, refers to namespaces that can be accessed directly.
When we access a variable, we will follow the order of LEGB to lookup:
- L->local. That is, local variables, such as variables defined in def or lambda.
- E-> enclosing function locals. That is, the variable in the closure.
- G->global (module). Global variables.
- B->built-in. Built-in variables, such as Len ()/keyerror.
When we access an attribute through an instance, self.x, its lookup order is:
- Instance Properties
- Class properties
- The parent class property. By MRO (method resolution Order)
Give a chestnut a more intuitive point.
s = ' Global ' class Foo (object): s = ' class ' def __init__ (self): print S #全局变量, output global print Foo.s #类属性, Output class print Self.s #实例属性中没找到, so look in the class properties, Output class Self.s = ' instance ' #创建了个实例属性 print Self.s #实例属性能找到, Output Instancefoo ()
Elegant python-scope and lookup strategies