Python本身没有任何机制阻止你干坏事,一切全靠自觉!
这句话用来说明Python中类和对象的访问控制很贴切,因为,本质上,Python并没有任何访问控制(变量无需申明,就更没有private这样的字眼)。
“_”开头的成员是可以访问的
给成员前面加上“_”表示:我是用于内部的,但是你可以直接访问我。
“__”开头的成员只是不能直接访问
给成员前面加上“__”表示:我是用于内部的,你不能直接访问我,但是高手可以这样来访问:
>>>
>>> class student():
... __name = 'aa'
...
>>> stu1 = student()
>>> stu1.__name # can not access
Traceback (most recent call last):
File "", line 1, in
AttributeError: 'student' object has no attribute '__name'
>>> stu1._student__name
'aa'
>>>
除非闲的蛋疼,否则就不要干这样的事情!
“__xxxx__”这样定义的成员
这样的定义,表示特殊用途,可以直接访问。
比如python的docstring,就是__doc__。