Một ví dụ là giá trị một năm 1000 từ:
class test(object):
def __init__(self):
self.a = 0
self._b = 0
def change_a(self):
self.a = 1
def change_b(self):
self._b = 1
def display_b(self):
print "_b: ", self._b
như-là, kết quả là:
c = test()
c.a
0
#expected.
c.b
AttributeError: 'test' object has no attribute 'b'
# because _b is private
c.display_b()
_b: 0
# methods can display private variables.
tại gán một số giá trị:
c.a=100
c.b=100
c.a
100
# again, expected
c.b
100
# as expected
c.display_b()
_b: 0
# again, private variable can't be changed directly.
bây giờ gọi nội bộ funcs:
c.change_a()
c.change_b()
c.a
1
# expected
c.b
100
# that c.change_b() function isn't changing the externally created variable c.b
c.display_b()
1
#but it changed the internal variable _b
Có thể trùng lặp [Ý nghĩa của một đơn và dấu gạch dưới kép trước tên đối tượng là gì?] (http://stackoverflow.com/questions/1301346/what-is -the-nghĩa-of-a-đơn-và-một-đôi-gạch dưới-trước-một-đối tượng-tên) – MackM