gpt4 book ai didi

python-3.x - python 3中的函数注释得到 "name not defined"错误

转载 作者:行者123 更新时间:2023-12-01 04:39:19 34 4
gpt4 key购买 nike

我正在尝试使用 python3 类型注释功能。

这是一些没有注释的玩具函数:

def fa(func, *args):
return func(*args)
def fb(x:str):
return x + " returned."
fa(fb, "Newton")

这些工作正常。但是一旦我为 fa 添加一些注释,它就会出错:

def fa(func:function, *args):
return func(*args)
def fb(x:str):
return x + " returned."
fa(fb, "Newton")

Traceback (most recent call last):
File "/usr/local/lib/python3.4/site-packages/IPython/core/interactiveshell.py", line 2883, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-17-193b74f82e47>", line 1, in <module>
def fa(func:function, *args):
NameError: name 'function' is not defined

为什么会发生这种情况,我该如何解决?

最佳答案

正如错误消息告诉您的那样,名称 function 未定义。如果您想将提示作为函数,请将其放在引号中:

def fa(func: 'function', *args):

关于python-3.x - python 3中的函数注释得到 "name not defined"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27461035/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com