_single_leading_underscore: Python 沒有真正的 private methods (只能同一個程式內使用的 methods),
所以使用一個底線 _ 開頭的 method 表示其他程式不能存取這個 method。
例如:mypy.py 有兩個 classes myPy, _myPy1,在 mypy.py 的程式中直接呼叫都可以使用。
pyuser@deyu:~/zzz$ vi mypy.py
pyuser@deyu:~/zzz$ python mypy.py
my first python myPy
my first python myPy1
pyuser@deyu:~/zzz$ vi test.py
pyuser@deyu:~/zzz$ python test.py
my first python myPy
my first python myPy1
my first python myPy
Traceback (most recent call last):
File "/home/pyuser/zzz/test.py", line 6, in <module>
_myPy1()
^^^^^^
NameError: name '_myPy1' is not defined. Did you mean: 'myPy'?
[dywang@deyu zzz]$ vim mypy.py
[dywang@deyu zzz]$ cat mypy.py
#!/usr/bin/python3
# coding: utf-8
class _myPy1:
def __init__(self):
print ("my first python myPy1")
class myPy:
def __init__(self):
print ("my first python myPy")
myPy()
_myPy1()
[dywang@deyu zzz]$ ./mypy.py my first python myPy my first python myPy1
myPy() 及 _myPy()。
[dywang@dywIssd zzz]$ vim test.py [dywang@dywIssd zzz]$ cat test.py #!/usr/bin/python3 from mypy import * myPy() _myPy1()
myPy() 印出 "my first python myPy",但 _myPy() 則出現錯誤,因為 _myPy() 是 mypy.py 中的 private method,只能在 mypy.py 中執行,無法在 test.py 執行。
[dywang@dywIssd zzz]$ ./test.py
my first python myPy
my first python myPy1
my first python myPy
Traceback (most recent call last):
File "./test.py", line 7, in <module>
_myPy1()
NameError: name '_myPy1' is not defined