python - 函数参数 dtype 声明不起作用?
问题描述
为什么这不回馈'12'?
'+' 符号应该连接两个字符串,而不是添加它们。
def foo(a:str, b:str):
print(a+b)
foo(1,2)
3
解决方案
这不是注释的用途。注释是元数据,而不是 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
推荐阅读
- java - 如何将此大代码转换为 Java 8 lambda 表达式
- python-3.x - 将原始字符串分配给变量时 Python3 中的错误
- python - 如何在 Windows 10 上使用 Python(无需下载)从 Youtube URL 流式传输音频?
- c# - 将数据从 Access 插入 csv 文件的有效方法
- firebase - Firebase 和 Node,js:从用户的 Gmail 发送电子邮件?
- r - 在 usmap 包中使用 plot_usmap() 函数时遇到问题
- tomcat - 在 tomcat 服务器上设置 nonce
- laravel - 为什么在 Laravel 6 中调度作业时作业表为空?
- php - 将一维键值数组转换为二维 kay 值数组,每第 n 个键具有新的键名
- google-apps-script - ARRAYFORMULA 和 COUNTA 仅计数到当前行