_xx 單下劃線開頭
Python中沒有真正的私有屬性或方法,能夠在你想聲明爲私有的方法和屬性前加上單下劃線,以提示該屬性和方法不該在外部調用.若是真的調用了也不會出錯,但不符合規範.python
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
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
__xx 雙下劃線開頭
雙下劃線開頭,是爲了避免讓子類重寫該屬性方法.經過類的實例化時自動轉換,在類中的雙下劃線開頭的屬性方法前加上」_類名」實現.web
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
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
__xx__
此種寫法爲Python內建屬性方法,最好不要在外部調用app