class?Teacher(object):
????def?__init__(self,?name,score):
????????self.name?=?name
????????self.__score?=?score
w=Teacher('ab',22)
print?w._Teacher__score??????#對于私有屬性這樣為什么就可以訪問啊?還有一個問題class?Student(object):
????def?__init__(self,?name,?score):
????????self.name?=?name
????????self.__score?=?score
????@property
????def?score(self):
????????return?self.__score
????@score.setter
????def?score(self,?score):
????????if?score?<?0?or?score?>?100:
????????????raise?ValueError('invalid?score')
????????self.__score?=?score
????@property
????def?grade(self):
????????if?score>=90:
????????????return?'A'
????????elif?score>=60:
????????????return?'B'
????????return?'C'
s?=?Student('Bob',?59)
s.__score(1000)
print?s.__score#這里可以正常打印1000,為什么?
s.score=1000
print?s.score#這里就會報錯?又是為什么?
1 回答

asd8532
TA貢獻(xiàn)143條經(jīng)驗 獲得超187個贊
雙下劃線開頭其實只是一種讓程序員遵守的命名規(guī)范。其中的w._Teacher__score?是python里私有變量軋壓(Private name mangling)技術(shù),可以訪問私有變量,有人說是一種靈活的技巧,認(rèn)識就可以了
def?prin(self): ????????print?self.__score#定義一個輸出__score的函數(shù) ? s?=?Student('Bob',?59) s.__score=1000 print?s.__score#我們以為已經(jīng)修改了__score但事實上并沒有,這個__score和我們的self.__score不是同一個 s.prin() #輸出結(jié)果是,而不是2個1000 ##59
添加回答
舉報
0/150
提交
取消