about 3 years ago

Prefer Public Attributes Over Private Ones

Python 裡頭沒有真正的 "private variable",想存取都可以存取得到。

We are all consenting adults here

下面的程式看起來我們沒辦法得到 __private_field

class MyObject(object):
    def __init__(self):
        self.public_field = 5
        self.__private_field = 10

    def get_private_field(self):
        return self.__private_field

foo = MyObject()
print(foo.__private_field) # AttributeError

但其實只是名稱被改掉而已

print(foo.__dict__)
# {'_MyObject__private_field': 10, 'public_field': 5}


print(foo._MyObject__private_field)

一般來說 Python 慣例是在變數前加一個底線代表 protected variable,作用在於提醒開發者使用上要注意。

Use one leading underscore only for non-public methods and instance variables

class MyClass(object):
    def __init__(self, value):
        # This stores the user-supplied value for the object.

        # It should be coercible to a string. Once assigned for

        # the object it should be treated as immutable.

        self._value = value

    def get_value(self):
        return str(self._value)

class MyIntegerSubclass(MyClass):
    def get_value(self):
        return self._value

foo = MyIntegerSubclass(5)
assert foo.get_value() == 5

雙底線的命名方式是為了避免父類跟子類間的命名衝突,除此之外盡量避免使用這種命名。

← Effective Python 心得筆記: Item 26 Effective Python 心得筆記: Item 28 →
 
comments powered by Disqus