私有屬性變數不能從物件外部訪問,而只能通過訪問器方法
class secretive:
def __inaccessible(self):
print("bet you can't see me ...")
def accessible(self):
print("the secret message is:")
self.__inaccessible()
>>> s = secretive()
>>> s.__inaccessible()
traceback (most recent call last):
file "", line 1, in attributeerror: secretive instance has no attribute '__inaccessible'
>>> s.accessible()
the secret message is:
bet you can't see me ..
現在從外部不能訪問 __inaccessible ,但在類中(如 accessible 中)依然可以使用它
如果你不希望名稱被修改,又想發出不要從外部修改屬性或方法的訊號,可用乙個下劃線打
頭。這雖然只是一種約定,但也有些作用。例如, from module import * 不會匯入以乙個下劃線打頭的名稱
python類私有屬性
python中沒有private關鍵字,想要建立乙個類私有的變數需要通過命名規則來實現 在變數名之前加兩個下劃線 name,則在類外部就不能直接通過例項.name訪問,具體原理python編譯器將其命名修改為了 類名 name,通過其實例項.類名 name還是可以訪問 class test obje...
python類的共有屬性 私有屬性 例項屬性
類的共有屬性 私有屬性 例項屬性 class parent i 1 j 2 class child parent m 3 n 4 def init self,age,name self.age age self.name name def des self print self.name,self....
Python 類的私有屬性和私有方法
xx 公有變數 xx 公有變數或方法,不能通過import匯入其他模組 只有模組內部使用 類物件和子類可以訪問 xx 私有變數或方法 偽私有 類外部不能直接訪問。xx 公有變數或方法,子類可以訪問。魔法方法或屬性 例如 init 不推薦這樣命名。xx 公有變數或方法。一般為了避免和python關鍵字...