Skip to Content
Python 技術手冊 第三版
book

Python 技術手冊 第三版

by lex Martelli, Anna Martelli Ravenscroft, Steve Holden
January 2018
Intermediate to advanced content levelIntermediate to advanced
856 pages
17h 17m
Chinese
GoTop Information, Inc.
Content preview from Python 技術手冊 第三版
類別與實體
|
145
@property
def area(self):
'''area of the rectangle'''
return self.width * self.height
@area.setter
def area(self, value):
scale = math.sqrt(value/self.area)
self.width *= scale
self.height *= scale
為何特性很重要
特性關鍵的重要性在於,它們的存在讓你能夠絕對安全地(並且確實是可
取的)對外提供公開的資料屬性作為你類別公開介面的一部分。在你的類
別或需要對它多型的其他類別之未來版本中,若有必要在屬性被參考、重
新繫結或解除繫結時執行某些程式碼,你就知道你可以將那個普通的屬性
變為一個特性,並且得到想要的效果,而不會對使用你類別的任何程式碼
(即「客戶端程式碼」,「client code」)有任何衝擊。這能讓你避開缺乏特
性或等效機制的 OO 語言中所需的古怪慣用語,例如
存取器
accessor
變動器
mutator
方法。舉例來說,客戶端程式碼可以單純使用像這樣的
自然慣用語:
some_instance.widget_count += 1
而非像這樣被迫進到存取器和變動器扭曲的巢穴之中:
some_instance.set_widget_count(some_instance.get_widget_count() + 1)
如果你曾經試著編寫你會想要將它們取名為
get_this ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

測試驅動開發|使用 Python

測試驅動開發|使用 Python

Harry J.W. Percival
Linux 内核观测技术BPF

Linux 内核观测技术BPF

David Calavera, Lorenzo Fontana

Publisher Resources

ISBN: 9789864766819