Data Hiding
Python dùng double underscore trước tên attribute để làm cho chúng inaccessible/private (ẩn đi).
Ví dụ cơ bản
class MyClass:
__hiddenVar = 0
def add(self, increment):
self.__hiddenVar += increment
print(self.__hiddenVar)
obj = MyClass()
obj.add(3) # 3
obj.add(8) # 11
print(obj.__hiddenVar) # AttributeError
Truy cập attribute bị ẩn (name mangling)
class MyClass:
__hiddenVar = 12
def add(self, increment):
self.__hiddenVar += increment
print(self.__hiddenVar)
obj = MyClass()
obj.add(3) # 15
obj.add(8) # 23
print(obj._MyClass__hiddenVar) # 23 - truy cập qua mangled name
Kết quả
15 23 23
Lưu ý: Private method/attribute vẫn truy cập được từ bên ngoài, chỉ khó hơn. Python không có gì thực sự private - tên private method/attribute bị mangle/unmangle on the fly để ngăn truy cập bằng tên gốc.