热线电话:13121318867

登录
2019-02-20 阅读量: 825
python如何将数据隐藏?

在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'
0.0000
2
关注作者
收藏
评论(0)

发表评论

暂无数据
推荐帖子