---
title: "Python-特殊的下划线"
author: "mingren135"
date: "2012-10-21T13:01:58Z"
tags: []
categories: ["编程语言"]
slug: "python"
draft: false
lastmod: "2012-10-21T13:02:49Z"
id: 1702436
url: "https://mingren135.iteye.com/blog/1702436"
---

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，目的就是以防子类意外重写基类的方法或者属性。
```