名稱前雙底線

  1. __double_leading_underscore: 在一個 class 中 method 使用雙底線在名稱前面,且最後沒有底線。例如:class myPy 中的 method __method,則其全名為 _myPy__method
    pyuser@deyu:~/zzz$ vi mypy2.py
    pyuser@deyu:~/zzz$ cat mypy2.py
    #!/usr/bin/python
    
    class _myPy1:
    	def __init__(self):
    		print("my first python myPy1")
    class myPy:
    	def __init__(self):
    		print("my first python myPy")
    	def __method(self):
    		print("method in class myPy")
    
    if __name__ == "__main__":
    	print(__name__)
    	myPy()._myPy__method()
    	_myPy1()
    else:
    	print(__name__)
    
  2. 執行 mypy2.py,印出變數 __name____main__,執行 myPy()._myPy__method() 就是執行 class myPy 中的 method __method()
    pyuser@deyu:~/zzz$ python mypy2.py
    __main__
    my first python myPy
    method in class myPy
    my first python myPy1
    
  3. 撰寫 test2.py,使用 form mypy2 import * 從檔案 mypy2.py 匯入所有 classes,印出 myPy 的變數 __name__,執行 myPy._myPy__method()_myPy1
    pyuser@deyu:~/zzz$ vi test2.py
    pyuser@deyu:~/zzz$ cat test2.py
    #!/usr/bin/python
    
    from mypy2 import *
    
    myPy.__name__
    myPy()._myPy__method()
    _myPy1()
    
  4. 執行 test2.py,印出 myPy 的變數 __name__ 為 mypy2,執行 myPy()._myPy__method() 正常輸出,但執行 _myPy1() 則出現錯誤。
    pyuser@deyu:~/zzz$ python test2.py
    mypy2
    my first python myPy
    method in class myPy
    Traceback (most recent call last):
      File "/home/pyuser/zzz/test2.py", line 7, in <module>
        _myPy1()
        ^^^^^^
    NameError: name '_myPy1' is not defined. Did you mean: 'myPy'?