python - 为什么执行委托(delegate)函数时 Python 回溯很糟糕

标签 python events delegates callable traceback

我有一个允许事件委托(delegate)模式的搜索类。其他类可以注册一个在搜索更新时调用的函数。

当出现问题时,回溯不会显示接收器功能。例如:

我的搜索类运行这个...

# ----------- Search.py -----------
# class Search ...snip...
    def connect(self, fn):
        self.__updateDelegates.append(fn)

    def onTextChanged(self):
        # ...snip...
        # Execute all event delegates
        for fn in self.__updateDelegates:
            fn(search_pattern)

...如果委托(delegate)函数签名错误...

# ----------- Foo.py -----------
from search import Search
# class Foo ...snip...
    def __init__(self):
        search = Search()
        search.connect(self.onSearchUpdate)

    def onSearchUpdate(self): # <- Wrong on purpose. Should have another argument
        # Do something.

...我看到这个...

# Traceback (most recent call last):
#   File "search.py", line 287, in onTextChanged
#     fn(search_pattern)
# TypeError: onSearchUpdate() takes exactly 1 argument (2 given)

请注意,异常消息中的委托(delegate)函数名称是正确的,但回溯没有达到那么远。

该错误是因为委托(delegate)签名应该有一个模式参数。问题是回溯没有显示错误发生的位置。它应该进一步返回到引用所指向的函数对象。

知道如何解决这个问题吗?

注意:我更新了代码和解释。我不想用额外的代码来混淆这个问题,但我觉得我需要展示更多。这并没有显示是什么触发了函数onTextChanged()。这实际上是 Qt 小部件实现的一部分,当有人在 QLineEdit 中键入内容时,它会运行此函数。所以模式是,父窗口小部件创建搜索窗口小部件,然后连接其函数以在文本更改时调用。我希望这会有所帮助。

最佳答案

假设 onSearchUpdate 是类 Foo 上的一个方法:

class Foo(object):
    def __init__(self,search_pattern):
        self.search_pattern=search_pattern
    def onSearchUpdate(self):
        pass #do something with search_pattern

现在在Search类中,您以某种方式填充__updateDelegates:

pattern=['foo','bar','baz']

class Search(object):
    def __init__(self):
       self.__updateDelegates=[]
       for i in range(3):
           self.__updateDelegates(Foo(pattern[i]).onSearchUpdate)

现在,当您通过 __updateDelegates 调用 onSearchUpdate 时,您只需执行以下操作:

for func in self.__updateDelegates:
    func()

这可能不是您的代码的结构(很难用您的代码片段来判断),但希望这能说明问题。

或者,也许 onSearchUpdate 应该有第二个参数?

def onSearchUpdate(self,pattern):
   pass # snip ...

关于python - 为什么执行委托(delegate)函数时 Python 回溯很糟糕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11584846/

相关文章:

html - 带指针事件的 iframe : none; but with a div inside it that has pointer-events: auto;

c# - 在 C# 中优化多个调度通知算法?

javascript - React Native - 可触摸和胜利图表

c# - 使用 delegate/BeginInvoke 在 C# 中将调用者与被调用者解耦

iPhone:应用程序委托(delegate)中的 NSTimer 无效导致应用程序崩溃

python - 从嵌套列表中剥离文本并将内容保存到 csv 文件中

python - 如何在mlflow中记录Hydra的多次运行

python - 将 numpy.random.get_state() 写入文件

python - 如何在 Windows 上从 python 启动守护进程?

swift - 检测 float 的变化