简体   繁体   English

python 3中的函数注释获取“名称未定义”错误

[英]Function annotation in python 3 get “name not defined” error

I am trying to use python3 type annotation features. 我正在尝试使用python3类型注释功能。

Here is some toy functions without annotation: 这是一些没有注释的玩具功能:

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

These work ok. 这些工作正常。 But once I add some annotation for fa , it goes awry: 但是,一旦我为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

Why is this happening and how can I work around it? 为什么会发生这种情况,我该如何解决?

As the error message tells you, the name function isn't defined. 如错误消息所示,未定义名称function If you want to hint as a function, put it in quotes: 如果要将提示作为函数,请将其用引号引起来:

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

Because you define a variable in function parameters,but that parameter is not exist out of function.You have to write 因为您在函数参数中定义了一个变量,但是该参数在函数外并不存在。您必须编写

fa(function="Newton") FA(功能= “牛顿”)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM