Python Private

Python中,設置為Private的變數或方法,外界還是可以透過特殊方式去強制使用。雖然沒有像其他程式語言具有強制力,但也已經將該變數或方法是該模組或類別私有的信息告訴外界,外界只要遵守一般的使用情境,是不會呼叫到這些私有的變數或方法的。

PythonPrivate分為以下兩種:

module privates

是以一個底線_開頭的變數或函式。

  1. from . import *時,會自動忽略一個底線_開頭的變數或函式。
  2. 強制使用直接指定變數或函式名稱from . import _var_name, _func_name

例如:

# moduleA.py
_name = 'Bob'

def _hello():
    print('Hello', _name)

# moduleB.py
from moduleA import *
_hello()

# moduleC.py
from moduleA import _hello
_hello()

執行結果:

# moduleB.py
NameError: name '_hello' is not defined

# moduleC.py
Hello Bob

class privates

在類別中,以兩個底線_開頭的變數或方法。

  1. 物件被建立時,兩個底線_開頭的變數或方法會被加上_ClassName的前綴。
  2. 強制使用直接在變數或方法前,加上_ClassName的前綴即可。
  3. 使用dir(object)可以取得該物件已經加上前綴的變數或方法名稱。

例如:

class Staff(): 

    def __init__(self, name):
        self.name = name

    def __hello(self):
        print('Hello', self.name)

if __name__ == "__main__":
    s = Staff('Bob')
    print(dir(s))
    s.__hello()
    s._Staff__hello()

執行結果:

# s.__hello()
AttributeError: 'Staff' object has no attribute '__hello'

# s._Staff__hello()
Hello Bob

__all__

__all__用來設定模組中哪些類別、方法或變數可以被其他模組import。當其它模組from . import *時,只有在__all__名單中的類別、方法或變數會被import進來。

例如:

# moduleA
__all__ = ['id', 'get_name']

id = '001'
name = 'Bob'

def get_id():
    print('Your id is', id)

def get_name():
    print('Your name is', name)

class Staff():
    def __init__(self, name):
        self.name = name

    def get_name(self):
        print('Your name is', self.name)

# moduleB
from moduleA import *

print(id)
print(name)

get_id()
get_name()

s = Staff('Bob')

執行結果:

# print(id)
001

# print(name)
NameError: name 'name' is not defined

# get_id()
NameError: name 'get_id' is not defined

# get_name()
Your name is Bob

# s = Staff('Bob')
NameError: name 'Staff' is not defined

results matching ""

    No results matching ""