almost 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


# {'_MyObject__private_field': 10, 'public_field': 5}


一般來說 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