用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 妈妈生日祝福语简短励志