_xx 單下划線開頭
Python中沒有真正的私有屬性或方法,可以在你想聲明為私有的方法和屬性前加上單下划線,以提示該屬性和方法不應在外部調用.如果真的調用了也不會出錯,但不符合規范.
def singleton(cls):
_instance = {}
def _singleton(*args, **kargs):
if cls not in _instance:
_instance[cls] = cls(*args, **kargs)
return _instance[cls]
return _singleton
@singleton
class A(object):
a = 1
def __init__(self, x = 0):
self.x = x
a1 = A(2)
a2 = A(3)
print id(a1)
print id(a2)
print a1.x
print a2.x
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
__xx 雙下划線開頭
雙下划線開頭,是為了不讓子類重寫該屬性方法.通過類的實例化時自動轉換,在類中的雙下划線開頭的屬性方法前加上”_類名”實現.
class A(object):
def __init__(self, x):
self.__a = 2
self.x = x
def __b(self):
self.x = 3
a = A(2)
print a.x, a._A__a
a._A__b()
print a.x
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
__xx__
此種寫法為Python內建屬性方法,最好不要在外部調用