关于python装饰器的一个小问题。

发布时间 2023-10-10 02:23:22作者: fineee_e

今天在使用python的装饰器的时候,出现了一些小问题。

下面是装饰器的代码。

def try_except_decorator(func):
    def wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except Exception as e:
            print(f'发生错误,错误在于:{e}')

装饰器的代码非常的平常,就是一个try-except的功能。

然后是调用装饰器的代码部分:

    @try_except_decorator
    def show_next_word(self):
        self.current_word_index = (self.current_word_index + 1) % len(self.word_list)
        print('当前单词序列:' + str(self.current_word_index))
        self.word_label.setText(self.word_list[self.current_word_index].english)
        self.chinese_label.setText(self.word_list[self.current_word_index].chinese)

这部分也很平常,就是当前单词序列索引的增加。

下面是方法连接的部分:

self.reme_button.clicked.connect(self.show_next_word)

但是出现了报错:

TypeError: argument 1 has unexpected type 'NoneType'

错误描述是在connec方法中我传入了Nonetype对象。

先说这个问题的解决办法:使用lambda来包装创建一个匿名函数。代码如下:

self.reme_button.clicked.connect(lambda: self.show_next_word())

这样就好了。

对于这个小问题我的理解是,在使用装饰器并返回func之后,返回的是func 的调用结果,而非是函数。装饰器如其名,经过装饰后的结果并不是跟原来一模一样的。而lambda作为一个小函数,接收调用结果也就是 self.show_next_word()作为参数,并对其进行包装,做成connect可以接收的方法。