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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值