__private_attr:两个下划线开头,声明该属性为私有,不能在类的外部被使用或直接访问。在类内部的方法中使用时 self.__private_attrs。 比如:self.__wife
__private_method:两个下划线开头,声明该方法为私有方法,不能在类的外部调用。 在类的内部调用方式为self.__private_methods
运行结果:
1 2 2 Traceback (most recent call last): File "Count.py", line 17, in <module> print counter.__privateCount AttributeError: MyCounter instance has no attribute '__privateCount'Python不允许实例化的类访问私有数据,但你可以使用 object._className__attrName 访问属性,将如下代码替换以上代码的最后一行代码:
print counter._MyCounter__privateCount运行结果:
1 2 2 2__foo__: 定义的是特殊方法,一般是系统定义名字 ,类似__init__()之类的。
_foo: 以单下划线开头的表示的是 protected 类型的变量,即保护类型只能允许其本身与子类进行访问,不能用于 from module import *
__foo: 双下划线的表示的是私有类型(private)的变量, 只能是允许这个类本身进行访问了。
更多内容请关注微信公众号
