名稱前單底線

  1. Python 中的函式 (function) 與方法 (method) 簡單的區分是:function 是一段區塊程式碼,透過呼叫及傳入參數後將結果輸出或回傳;method 不同於 function 的是 method 定義在類別 (class) 中,透過執行該類別的物件 (object) 中的 method 得到輸出。
  2. _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()
    
  3. 直接執行 mypy.py,不論有無前底線的 method 都可以執行。
    [dywang@deyu zzz]$ ./mypy.py 
    my first python myPy
    my first python myPy1
    
  4. 撰寫 test.py 從 mypy 匯入所有模組,執行 myPy()_myPy()
    [dywang@dywIssd zzz]$ vim test.py 
    [dywang@dywIssd zzz]$ cat test.py
    #!/usr/bin/python3
    
    from mypy import *
    
    myPy()
    _myPy1()
    
  5. 執行 test.py,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