在我构建的一个特定类中,它本质上充当了用户定义函数的包装器,除了实例化之外,用户只需要使用我的类中的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中显式调用时才运行?在
decorator行创建类的一个实例:
然后使用该实例进行实际的装饰;您实际上是这样做的:
^{pr2}$因为
decorator
是类的一个实例,decorator(testfcn)
调用由ClassIBuilt.__call__()
方法处理,并且该方法不返回任何结果:没有
return
语句意味着None
被返回,因此testfcn
被设置为None
。您不能调用None
,这会导致您看到的异常。在您的
^{4}$__call__
应该返回包装:现在,
testfcn
被绑定到wrapper()
函数,然后该函数调用原来的修饰函数。在相关问题 更多 >
编程相关推荐