python单/双下划线使用

本文详细介绍了Python中私有成员的定义方式及其访问方法。针对单下划线和双下划线开头的成员变量和方法进行了区分,并给出了具体的示例代码。通过名称改编机制可以访问到真正意义上的私有成员。

在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了。
 1 class Foo():
 2     def __init__():
 3         ... 
 4     def public_method():
 5         print 'This is public method'
 6     def __fullprivate_method():
 7         print 'This is double underscore leading method'
 8     def _halfprivate_method():
 9         print 'This is one underscore leading method'
10 
11 f = Foo()
12 f.public_method() # OK
13 f.__fullprivate_method() # Error occur
14 f._halfprivate_method() # OK

上文已经说明了,python中并没有真正意义的private,见以下方法便能够访问__fullprivate_method()

  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值