python 物件導向(二)--訪問限制

來源:互聯網
上載者:User

標籤:一個   art   成功   class   print   private   機制   code   無效   

在Class內部,可以有屬性和方法,而外部代碼可以通過直接調用執行個體變數的方法來操作資料,這樣,就隱藏了內部的複雜邏輯。

但是,從前面Student類的定義來看,外部代碼還是可以自由地修改一個執行個體的namescore屬性:

 1 class Student(object): 2  3     def __init__(self, name, score): 4         self.name = name 5         self.score = score 6  7     def print_score(self): 8         print(‘%s: %s‘ % (self.name, self.score)) 9 10 instance = Student(‘Andy‘, 60)  # 類的執行個體11 print(instance.name)12 print(instance.score)

如果要讓內部屬性不被外部存取,可以把屬性的名稱前加上兩個底線__,在Python中,執行個體的變數名如果以__開頭,就變成了一個私人變數(private),只有內部可以訪問,外部不能訪問,所以,我們把Student類改一改:

 1 class Student(object): 2  3     def __init__(self, name, score): 4         self.__name = name 5         self.__score = score 6  7     def print_score(self): 8         print(‘%s: %s‘ % (self.__name, self.__score)) 9 instance = Student(‘Andy‘, 60)  # 類的執行個體10 print(instance.name)11 12 會提示:13       AttributeError: ‘Student‘ object has no attribute ‘name‘

改完後,對於外部代碼來說,沒什麼變動,但是已經無法從外部存取執行個體變數.__name執行個體變數.__score了,這樣就確保了外部代碼不能隨意修改對象內部的狀態,這樣通過訪問限制的保護,代碼更加健壯。

但是如果外部代碼要擷取name和score怎麼辦?可以給Student類增加get_nameget_score這樣的方法:

 1 class Student(object): 2  3     def __init__(self, name, score): 4         self.__name = name 5         self.__score = score 6  7     def get_name(self): 8         return self.__name 9 10     def get_score(self):11         return self.__score12 13     def print_score(self):14         print(‘%s: %s‘ % (self.__name, self.__score))15 instance = Student(‘Andy‘, 60)  # 類的執行個體16 print(instance.get_name())

但倘若又要允許外部代碼修改score怎麼辦?可以再給Student類增加set_score方法:

1 class Student(object):2     ...3 4     def set_score(self, score):5         self.__score = score

你也許會問,原先那種直接通過instance.score = 60也可以修改啊,為什麼要定義一個方法大費周折?因為在方法中,可以對參數做檢查,避免傳入無效的參

1 class Student(object):2     ...3 4     def set_score(self, score):5         if 0 <= score <= 100:6             self.__score = score7         else:8             raise ValueError(‘bad score‘)

需要注意的是,在Python中,變數名類似__xxx__的,也就是以雙底線開頭,並且以雙底線結尾的,是特殊變數,特殊變數是可以直接存取的,不是private變數,所以,不能用__name____score__這樣的變數名。

有些時候,你會看到以一個底線開頭的執行個體變數名,比如_name,這樣的執行個體變數外部是可以訪問的,但是,按照約定俗成的規定,當你看到這樣的變數時,意思就是,“雖然我可以被訪問,但是,請把我視為私人變數,不要隨意訪問”。

雙底線開頭的執行個體變數是不是一定不能從外部存取呢?其實也不是。不能直接存取__name是因為Python解譯器對外把__name變數改成了_Student__name,所以,仍然可以通過_Student__name來訪問__name變數:

print(instance._Student__name)

結果:Andy

但是強烈建議你不要這麼幹,因為不同版本的Python解譯器可能會把__name改成不同的變數名。

總的來說就是,Python本身沒有任何機制阻止你幹壞事,一切全靠自覺。

最後注意下面的這種錯誤寫法:

 1 instance = Student(‘Andy‘, 60)  # 類的執行個體 2 print(instance.get_name()) 3  4 instance.__name=‘new Name‘ 5 print(instance.__name) 6  7 result: 8 Andy 9 new Name10 [Finished in 0.1s]

表面上看,外部代碼“成功”地設定了__name變數,但實際上這個__name變數和class內部的__name變數不是一個變數!內部的__name變數已經被Python解譯器自動改成了_Student__name,而外部代碼給bart新增了一個__name變數。

 

python 物件導向(二)--訪問限制

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.