且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

函数注释在python中给出错误?

更新时间:2022-12-07 18:02:10

两件事:

  1. 您必须以某种方式使用Python2.x. 功能注释仅在Python 3.x中受支持.如果尝试在Python 2.x中使用它们,则会得到SyntaxError:

  1. You must be using Python 2.x somehow. Function annotations are only supported in Python 3.x. If you try to use them in Python 2.x, you will get a SyntaxError:

>>> def f() -> int:
  File "<stdin>", line 1
    def f() -> int:
            ^
SyntaxError: invalid syntax
>>>

  • 如果未定义number(我相信是),则需要将其设置为字符串,以免得到NameError.下面是一个演示:

  • If number is undefined (which I believe it is), then you need to make it a string so that you don't get a NameError. Below is a demonstration:

    >>> def square_root(x:number, eps:number) -> float:
    ...     pass
    ...
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    NameError: name 'number' is not defined
    >>>
    >>> def square_root(x:'number', eps:'number') -> float:
    ...     pass
    ...
    >>>