python中有几种比较有意思的命名的方式,__xxx__ 、_name、__name,下面分别说它们的用处。
__xxx__
双下划线开头,双下划线结尾,表示的是特殊变量,是可以直接访问的,这种形式的类成员的函数尽量不要重载。在代码中我们经常见到这种方式命名。
def __init__(self, name)
_name
单下划线开头,有时候会看到这么命名的实例变量名,表示的是保护变量,虽然可以从外部访问,但是约定俗成不要随意访问这些实例变量。
__name
双下划线开头,表示的是私有变量,为了让内部属性不被外部访问。
>>>class Test(object):
... def __init__(self, name, id):
... self.name = name
... self.__id = id
...
>>>test = Test('Jack', 1)
>>>test.name
'Jack'
>>>test.id
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Test' object has no attribute 'id'
但是在python中还是有从外部访问变量id的方法:instance._ClassName__attribute
>>>test._Test__id
1