ITeye博客

Python-特殊的下划线

mingren135 · 2012-10-21 13:01 · 脚本语言 · 编程语言 · Markdown

1)看看下划线在模块变量命名的访问情况

 

a.py

corp = 'corp:taobao'  #public
_corp = '_corp:taobao' #obey python coding convention, consider it as private
__corp = '__corp:taobao' #private
__corp__='__corp__:taobao' #special, python system use, user should not define like it


b.py

from a import *

print corp #ok
print _corp  #Undefined variable: _corp
print __corp #Undefined variable: __corp
print __corp__ #Undefined variable: __corp__

 

2)下划线用在模块方法的情况和模块变量是一样的

 

3)看看下划线用在对象方法上的情况,可见在python对象中是没有严格意义上的private的

 

m = Manager('my', 200)

m._hello() #要用也没办法,not a good habit

m.__hello__() #not recommended

m.__hello() #AttributeError: Manager instance has no attribute '__hello'

m._Manager__hello() #name mangling就是将__fullprivate_method替换成了_Foo__fullprivate_method,目的就是以防子类意外重写基类的方法或者属性。

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。