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

ACa*_*lza 5 python annotations function

所以我做了一个函数,并想为其添加注释,但编译器一直给我一个错误:

def square_root(x:number, eps:number) -> float:
    pass
Run Code Online (Sandbox Code Playgroud)

编译器返回如下:

  File "/Users/albertcalzaretto/Google Drive/CSC148H1/e1/e1a.py", line 1
    def square_root(x, eps) -> float:
                            ^
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)

我从未使用过函数注释,并且阅读了一些有关它的资料,并且我不认为我所做的事情是错误的。

小智 4

两件事情:

  1. 您一定在以某种方式使用 Python 2.x。 仅 Python 3.x 支持函数注释。如果您尝试在 Python 2.x 中使用它们,您将得到SyntaxError

    >>> def f() -> int:
      File "<stdin>", line 1
        def f() -> int:
                ^
    SyntaxError: invalid syntax
    >>>
    
    Run Code Online (Sandbox Code Playgroud)
  2. 如果number未定义(我相信是这样),那么您需要将其设为字符串,这样您就不会得到NameError. 下面是一个演示:

    >>> 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
    ...
    >>>
    
    Run Code Online (Sandbox Code Playgroud)