2
已經有一個類似的問題"When and how to use the builtin function property() in python",但我這一個是不同的。Getter方法vs只讀屬性
我有一個需要一個方法來獲得的一些工作進展計數器類:
class Downloader():
def __init__(self, max_workers):
self.executor = ThreadPoolExecutor(max_workers)
@property
def unfinished_tasks_count(self):
return self.executor._work_queue.unfinished_tasks
我認爲這是更好地做到:
class Downloader():
...
def get_unfinished_tasks_count(self):
return self.executor._work_queue.unfinished_tasks
,因爲當它的屬性看界面(無需查看文檔和/或源代碼),它並不是顯式的,它是隻讀的計算屬性。當它是一種方法時,顯然它只是一個計算值的獲取者,並不是一個可由API客戶端設置的簡單屬性。
所以我的問題是:何時使用getter方法vs只讀屬性?
我想如果你想要它_read-only_,一個getter函數會更好。 – aIKid