使用对象作为函数

我正在阅读 Dusty Phillips 的一本 Python OOPs 书。我无法理解书中的特定程序,第 7 章 - Python 面向对象的快捷方式。代码的扩展版本可在此处获得

尽管该程序属于Functions are objects too主题,但所提供的程序还使用了一个奇怪的代码,我觉得这更像是相反的意思(将对象用作函数)。

我已经指出了代码中我有疑问的那一行。callback该变量如何TimedEvent像函数Timer类一样使用?这部分发生了什么。

import datetime

import time


class 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)


噜噜哒
浏览 124回答 2
2回答

qq_花开花谢_0

两个都是真的函数是对象:dir(f)对函数执行 a 以查看其属性对象可以用作函数:只需添加__call__(self, ...)方法并像函数一样使用对象。一般来说,可以使用类似语法调用的东西whatever(x, y, z)称为callables。该示例试图表明的是,方法只是对象属性,也是可调用对象。就像你会写obj.x = 5,你也会写obj.f = some_function。

白板的微信

是的,这个例子确实表明函数是对象。您可以将一个对象分配给callback属性,这试图表明您分配给的对象callback可以是一个函数。class&nbsp;TimedEvent: &nbsp;&nbsp;&nbsp;&nbsp;def&nbsp;__init__(self,&nbsp;endtime,&nbsp;callback): &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;self.endtime&nbsp;=&nbsp;endtime &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;self.callback&nbsp;=&nbsp;callback需要明确说明的是初始化。例如,您可以这样做:def&nbsp;print_current_time():&nbsp; &nbsp;&nbsp;&nbsp;print(datetime.datetime.now().isoformat()) event&nbsp;=&nbsp;TimedEvent(endtime,&nbsp;print_current_time) event.callback()这实际上会调用print_current_time,因为event.callback是print_current_time。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python