Chinaunix首页 | 论坛 | 博客
  • 博客访问: 313119
  • 博文数量: 60
  • 博客积分: 2781
  • 博客等级: 少校
  • 技术积分: 600
  • 用 户 组: 普通用户
  • 注册时间: 2010-05-23 16:42
文章分类

全部博文(60)

文章存档

2011年(33)

2010年(27)

分类: Python/Ruby

2011-04-26 08:17:03

在Python编程中经常会遇到函数(function),方法(method)及属性(attribute)以下划线'_'作为前缀,这里做个总结。
主要存在四种情形
  1. 1. object # public

  2. 2. __object__ # special, python system use, user should not define like it

  3. 3. __object # private (name mangling during runtime)

  4. 4. _object # obey python coding convention, consider it as private
通过上面的描述,1和2两种情形比较容易理解,不多做解释,最迷惑人的就是3和4情形。
在解释3和4情形前,首先了解下python有关private的描述,python中不存在protected的概念,要么是public要么就是private,但是python中的private不像C++, Java那样,它并不是真正意义上的private,通过name mangling(名称改编,下面例子说明)机制就可以访问private了。

针对 3:
  1. class Foo():
  2.     def __init__():
  3.         ...
  4.     
  5.     def public_method():
  6.         print 'This is public method'

  7.     def __fullprivate_method():
  8.         print 'This is double underscore leading method'

  9.     def _halfprivate_method():
  10.         print 'This is one underscore leading method'
然后我们实例化Foo的一个对象,看看结果就很清晰了:
  1. f = Foo()

  2. f.public_method() # OK

  3. f.__fullprivate_method() # Error occur

  4. f._halfprivate_method() # OK
上文已经说明了,python中并没有真正意义的private,见以下方法便能够访问__fullprivate_method()
  1. f._Foo__fullprivate()_method() # OK

  2. print dir(f)
  3. ['_Foo__fullprivate_method', '_halfprivate_method', 'public_method', ...]
所谓的name mangling就是将__fullprivate_method替换成了_Foo__fullprivate_method,目的就是以防子类意外重写基类的方法或者属性。

针对4:
从上面的例子可以看出,f._halfprivate_method()可以直接访问,确实是。不过根据python的约定,应该将其视作private,而不要在外部使用它们,(如果你非要使用也没辙),良好的编程习惯是不要在外部使用它咯。
同时,根据Python docs的说明,_object和__object的作用域限制在本模块内,见以下示例:
  1. '''
  2. A.py
  3. '''
  4. def _nok(): # __nok() same as _nok()
  5.     ...

  6. def ok():
  7.     ...
  1. '''
  2. B.py
  3. '''
  4. from A import *

  5. ok() # work well

  6. _nok() # error occur

  7. __nok() # error occur
通过上面的例子就能很好地把握有关下划线的细节了,平时还是需要多动手练练。
阅读(7124) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~