用Python隐藏数据
在类定义之外,对象的属性可能不可见。您需要使用双下划线前缀来命名属性,这样外部人就无法直接看到那些属性。
示例
#!/usr/bin/python
class JustCounter:
__secretCount = 0
def count(self):
self.__secretCount += 1
print self.__secretCount
counter = JustCounter()counter.count()
counter.count()
print counter.__secretCount输出结果
执行以上代码后,将产生以下结果-
1
2
Traceback (most recent call last):
File "test.py", line 12, in <module>
print counter.__secretCount
AttributeError: JustCounter instance has no attribute '__secretCount'Python通过内部更改名称以包括类名称来保护这些成员。您可以访问诸如object._className__attrName之类的属性。如果您按照以下方式替换最后一行,那么它对您有用-
......................... print counter._JustCounter__secretCount
执行以上代码后,将产生以下结果-
1 2 2
热门推荐
10 新人红包祝福语简短精辟
11 幼师给毕业祝福语简短
12 生日高考祝福语妹妹简短
13 下飞机祝福语简短英文
14 元宵发客户祝福语简短
15 爸妈金婚文案祝福语简短
16 新郎朋友红包祝福语简短
17 虎年五一祝福语大全简短
18 出阁宴祝福语姐姐简短