代码之家  ›  专栏  ›  技术社区  ›  Chris

函数参数dtype声明不起作用?

  •  1
  • Chris  · 技术社区  · 7 年前

    为什么这个不能返回“12”?
    “+”符号应该连接两个字符串,而不是添加它们。

    def foo(a:str, b:str):
        print(a+b)
    foo(1,2)
    3
    
    1 回复  |  直到 7 年前
        1
  •  5
  •   Martijn Pieters    7 年前

    这不是注释的用途。批注是 元数据 ,而不是Python转换数据的指令。

    Function definitions reference documentation :

    参数可能有如下形式的注释 : expression 在参数名称之后。任何参数都可以有注释,即使是表单的注释 *identifier **identifier .函数可能具有表单的返回注释 -> expression 参数列表之后。这些注释可以是任何有效的Python表达式,并在执行函数定义时进行计算。注释的计算顺序可能与它们在源代码中的显示顺序不同。 注释的存在不会改变函数的语义。

    (加粗emphisis mine)。

    例如 Python type hinting framework 使用注释将类型信息附加到用于静态分析的函数,验证代码是否实际传入了预期传入的类型。

    只需显式转换您的值;在通话中:

    foo(str(1), str(2))
    

    或在函数本身中:

    def foo(a, b):
        print(str(a) + str(b))
    

    或在装饰师中:

    import functools
    import inspect
    
    def typeconversion(f):
        """Converts arguments with a callable attached in the parameter annotation"""
        sig = inspect.signature(f)
    
        @functools.wraps(f)
        def wrapper(*args, **kwargs):
            # convert any argument (including defaults), for which there is a
            # callable annotation
            bound = sig.bind(*args, **kwargs)
            bound.apply_defaults()
            args = bound.arguments
            for param in sig.parameters.values():
                if param.annotation is not param.empty and callable(param.annotation):
                    args[param.name] = param.annotation(args[param.name])
    
            # call the function with the converted arguments
            result = f(*bound.args, **bound.kwargs)
    
            # convert the return value
            if sig.return_annotation is not sig.empty and callable(sig.return_annotation):
                result = sig.return_annotation(result)
    
            return result
        return wrapper
    

    演示:

    >>> @typeconversion
    ... def foo(a: str, b: str) -> int:
    ...     return a + b
    ...
    >>> foo(42, 101)
    42101