我正在閱讀 Dusty Phillips 的一本 Python OOPs 書。我無法理解書中的特定程序,第 7 章 - Python 面向對象的快捷方式。代碼的擴展版本可在此處獲得盡管該程序屬于Functions are objects too主題,但所提供的程序還使用了一個奇怪的代碼,我覺得這更像是相反的意思(將對象用作函數)。我已經指出了代碼中我有疑問的那一行。callback該變量如何TimedEvent像函數Timer類一樣使用?這部分發生了什么。import datetimeimport timeclass TimedEvent: def __init__(self, endtime, callback): self.endtime = endtime self.callback = callback def ready(self): return self.endtime <= datetime.datetime.now()class Timer: def __init__(self): self.events = [] def call_after(self, delay, callback): end_time = datetime.datetime.now() + \ datetime.timedelta(seconds=delay) self.events.append(TimedEvent(end_time, callback)) def run(self): while True: ready_events = (e for e in self.events if e.ready()) for event in ready_events: event.callback(self) ----------------> Doubt self.events.remove(event) time.sleep(0.5)
2 回答

qq_花開花謝_0
TA貢獻1835條經驗 獲得超7個贊
兩個都是真的
函數是對象:
dir(f)
對函數執行 a 以查看其屬性對象可以用作函數:只需添加
__call__(self, ...)
方法并像函數一樣使用對象。
一般來說,可以使用類似語法調用的東西whatever(x, y, z)
稱為callables。
該示例試圖表明的是,方法只是對象屬性,也是可調用對象。就像你會寫obj.x = 5
,你也會寫obj.f = some_function
。

白板的微信
TA貢獻1883條經驗 獲得超3個贊
是的,這個例子確實表明函數是對象。您可以將一個對象分配給callback
屬性,這試圖表明您分配給的對象callback
可以是一個函數。
class TimedEvent: def __init__(self, endtime, callback): self.endtime = endtime self.callback = callback
需要明確說明的是初始化。例如,您可以這樣做:
def print_current_time(): print(datetime.datetime.now().isoformat()) event = TimedEvent(endtime, print_current_time) event.callback()
這實際上會調用print_current_time
,因為event.callback
是print_current_time
。
添加回答
舉報
0/150
提交
取消