`
keep
  • 浏览: 103059 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

python name resolve

阅读更多

copy from <Learn pyton, 3rd edition>, P506

 

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.

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics