出现问题的原因:
我们都知道,Python 3中函数的类型是function,而我现在想要将一个函数作为参数传入另一个函数中,我的第一反应就是将function作为函数的默认值来传入。比较离谱的是VSCode的语法自动高亮机制依然给我高亮了……你亮啥啊该亮的时候不亮,不该亮的时候锃亮。
错误位置:def extract_number_from_prediction(predict_function:function,question:str,prediction:str):
报错信息:NameError: name 'function' is not defined
出错原因是Python 3就没有内置function这个类……
解决方案:
改用typing.Callable或者collections.abc.Callable(3.9 +)对象。(函数的抽象类)
typing.Callable:https://docs.python.org/3/library/typing.html#typing.Callable
collections.abc.Callable:https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable
先引入包:from typing import Union, Callable
Callable[[str], Union[int,float]]表示输入是str,输出是int或float的函数。
原代码改成:def extract_number_from_prediction(predict_function:Callable[[str], Union[int,float]],question:str,prediction:str):
参考资料:Python 3: “NameError: name ‘function’ is not defined” - Stack Overflow
本文讲述了在Python3中遇到的将函数作为参数传递时的NameError,原因在于Python3没有内置`function`类。解决方案是使用`typing.Callable`或`collections.abc.Callable`来表示可调用的对象。作者提供了修改后的代码示例和相关参考资料链接。
2866

被折叠的 条评论
为什么被折叠?



