在Python中,我们在属性名称之前使用双下划线(Or __),并且这些属性在外部不会直接可见。

class MyClass:

# Hidden member of MyClass

__hiddenVariable = 0

# A member method that changes

# __hiddenVariable

def add(self, increment):

self.__hiddenVariable += increment

print (self.__hiddenVariable)

# Driver code

myObject = MyClass()

myObject.add(2)

myObject.add(5)

# This line causes error

print (myObject.__hiddenVariable)

输出 :2

7

Traceback (most recent call last):

File “filename.py”, line 13, in

print (myObject.__hiddenVariable)

AttributeError: MyClass instance has

no attribute ‘__hiddenVariable’