首页 > 解决方案 > 函数参数 dtype 声明不起作用?

问题描述

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

def foo(a:str, b:str):
    print(a+b)
foo(1,2)
3

标签: pythonpython-3.xfunctionannotations

解决方案


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

函数定义参考文档

参数可以在参数名称之后具有“<code>: expression”形式的注释。任何参数都可以有注释,即使是那些形式为*identifier或的参数**identifier。函数可能在参数列表之后有“<code>-> expression”形式的“return”注解。这些注释可以是任何有效的 Python 表达式,并在执行函数定义时进行评估。注释的评估顺序可能与它们在源代码中出现的顺序不同。注释的存在不会改变函数的语义。

(粗体强调我的)。

例如,Python 类型提示框架使用注解将类型信息附加到函数以进行静态分析,验证代码是否实际传入了预期传入的类型。

只需明确转换您的值;在通话中:

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

推荐阅读