Skip to main content
 首页 » 编程设计

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

2024年11月01日9birdshome

所以我做了一个函数,想给它加注解,编译器一直报错:

def square_root(x:number, eps:number) -> float: 
    pass 

编译器返回:

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

我从未使用过函数注解,而且我已经阅读了一些关于它的资料,而且我认为我所做的并没有错。

请您参考如下方法:

两件事:

  1. 您一定是在使用 Python 2.x。 Function annotations仅在 Python 3.x 中受支持。如果您尝试在 Python 2.x 中使用它们,您将得到一个 SyntaxError:

    >>> def f() -> int: 
      File "<stdin>", line 1 
        def f() -> int: 
                ^ 
    SyntaxError: invalid syntax 
    >>> 
    
  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 
    ... 
    >>>