自定义装饰器不允许在主要的Python中调用函数

2024-06-30 08:05:47 发布

您现在位置:Python中文网/ 问答频道 /正文

在我构建的一个特定类中,它本质上充当了用户定义函数的包装器,除了实例化之外,用户只需要使用我的类中的2-3个主函数。我试图使我的类decorator兼容,这样用户就可以简单地构建自己的函数并使用decorator,而不是显式地从我构建的类中调用2-3个函数。我现在试着测试一下。在

主要:

from class_I_built import ClassIBuilt

def main():
    testfcn()


@ClassIBuilt('1', MessageConverter, timeout=10)
def testfcn():
    count = 0
    while count < 1000:
        count = count + 1

main()

建造类

^{pr2}$

如果不在main()中调用testfcn(),则会调用\uuCall_Uu方法,并正常发布开始和结束消息。但它不应该这样工作,因为如果我在main()中显式调用testfcn(),它应该只运行testfcn()。但是,如果我在main()中调用testfcn(),如上面所示,那么它将发送消息,但是我得到一个NoneType object is not callable error。在

输出/堆栈跟踪:

publishing start
publishing end
Traceback (most recent call last):
  File "Main.py", line 13, in <module>
    main()
  File "Main.py", line 4, in main
    testfcn()
TypeError: 'NoneType' object is not callable

为什么会出现错误,如何构造代码,使其仅在main中显式调用时才运行?在


Tags: 函数用户消息objectismaindefcount
1条回答
网友
1楼 · 发布于 2024-06-30 08:05:47

decorator行创建类的一个实例:

@ClassIBuilt('1', MessageConverter, timeout=10)

然后使用该实例进行实际的装饰;您实际上是这样做的:

^{pr2}$

因为decorator是类的一个实例,decorator(testfcn)调用由ClassIBuilt.__call__()方法处理,并且该方法不返回任何结果:

def __call__(self, decorator_function=1):
    self.publish_start('starting message')
    decorator_function(*args, **kwargs)
    self.publish_end('ending message')

没有return语句意味着None被返回,因此testfcn被设置为None。您不能调用None,这会导致您看到的异常。在

您的__call__应该返回包装:

^{4}$

现在,testfcn被绑定到wrapper()函数,然后该函数调用原来的修饰函数。在

相关问题 更多 >