Python类是否支持其他语言的事件? [英] Does Python classes support events like other languages?

查看:36
本文介绍了Python类是否支持其他语言的事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做我的第一个Python项目,而我的类中已经缺少事件了.也许在Python中它甚至没有被称为事件,但是我想在我的类中创建可以添加函数引用的组".在班上的某个时候,我组中的所有函数引用都将执行.

I'm working on my first Python project, and I'm already missing events in my classes. Perhaps it's not even called events in Python, but I would like to create "groups" in my classes to which function references can be added. At some point in my class all function references in my group would execute.

这是Python内置的吗?(我目前使用的是2.7)

Is this built into Python? (I'm using 2.7 at the moment)

推荐答案

Python没有内置任何类型的事件系统,但是可以很简单地实现它.例如:

Python doesn't have any sort of event system built-in, but it's could be implemented pretty simply. For example:

class ObjectWithEvents(object):
    callbacks = None

    def on(self, event_name, callback):
        if self.callbacks is None:
            self.callbacks = {}

        if event_name not in self.callbacks:
            self.callbacks[event_name] = [callback]
        else:
            self.callbacks[event_name].append(callback)

    def trigger(self, event_name):
        if self.callbacks is not None and event_name in self.callbacks:
            for callback in self.callbacks[event_name]:
                callback(self)

class MyClass(ObjectWithEvents):
    def __init__(self, contents):
        self.contents = contents

    def __str__(self):
        return "MyClass containing " + repr(self.contents)

def echo(value): # because "print" isn't a function...
    print value

o = MyClass("hello world")
o.on("example_event", echo)
o.on("example_event", echo)
o.trigger("example_event") # prints "MyClass containing \"Hello World\"" twice

这篇关于Python类是否支持其他语言的事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆