gpt4 book ai didi

python - 在 Python 中实现事件处理程序

转载 作者:行者123 更新时间:2023-12-01 07:57:45 24 4
gpt4 key购买 nike

我正在寻找如何实现具有可重写事件处理程序的对象的方法。

这是一个无法正常工作的代码,我想对其进行调整以使其正常工作:

class Button(object):
def __init__(self, id):
self.id = id
pass
def trigger_on_press(self):
self.on_press()
def trigger_on_release(self):
self.on_release()
def on_press(self):
# empty handler
print("Just an empty on_press handler from id=%s" % self.id)
pass
def on_release(self):
# empty handler
print("Just an empty on_release handler from id=%s" % self.id)
pass

btn = Button("btn")
btn.trigger_on_press()

def custom_handler(self):
print("Event from id=%s" % self.id)

btn.on_press = custom_handler
btn.trigger_on_press()

如何覆盖该特定实例的默认空 on_press 方法,以便它正确传递 self引用?

最佳答案

我建议采用这样的方法:您直接拥有一个属性(在本例中为func_on_press),该属性保存对函数(而不是方法)的引用。该函数接收一个作为对象的参数(我将其称为 obj 而不是 self,以表明它是一个函数)。

def default_empty_event_handler(obj):
print('empty handler for id={}'.format(obj.the_id))

class Button:
def __init__(self, the_id):
self.the_id = the_id
self.func_on_press = default_empty_event_handler
self.func_on_release = default_empty_event_handler

def trigger_on_press(self):
self.func_on_press(self) # we pass 'self' as argument to the function

def trigger_on_release(self):
self.func_on_release(self) # we pass 'self' as argument to the function

现在您可以随时更改该属性:

btn = Button('btn')
print('first trigger')
btn.trigger_on_press()

def custom_handler(obj):
print('custom handler for id={}'.format(obj.the_id))

btn.func_on_press = custom_handler
print('second trigger')
btn.trigger_on_press()

这将给出以下输出:

first trigger
empty handler for id=btn
second trigger
custom handler for id=btn

在我看来,这大大减少了类的代码(您定义了更少的方法)并且很容易理解。这对你有用吗?

关于python - 在 Python 中实现事件处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55879728/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com