Chr*_*ris 0 python annotations function python-3.x
为什么这不回馈'12'?
'+'符号应该连接两个字符串,而不是添加它们.
def foo(a:str, b:str):
print(a+b)
foo(1,2)
3
Run Code Online (Sandbox Code Playgroud)
这不是注释的用途.注释是元数据,而不是Python转换数据的指令.
从函数定义参考文档:
参数可以
: expression在参数名称后面具有" " 形式的注释.任何参数都可能具有注释,甚至是形式*identifier或注释的注释**identifier.函数可以-> expression在参数列表之后具有"返回"形式" "的注释.这些注释可以是任何有效的Python表达式,并在执行函数定义时进行评估.可以按照与源代码中出现的顺序不同的顺序评估注释.注释的存在不会改变函数的语义.
(大胆的emphisis我的).
例如,Python类型提示框架使用注释将类型信息附加到函数以进行静态分析,验证代码实际传递的是预期传入的类型.
只需明确转换您的值; 在通话中:
foo(str(1), str(2))
Run Code Online (Sandbox Code Playgroud)
或者在函数本身中:
def foo(a, b):
print(str(a) + str(b))
Run Code Online (Sandbox Code Playgroud)
或在装饰者:
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
Run Code Online (Sandbox Code Playgroud)
演示:
>>> @typeconversion
... def foo(a: str, b: str) -> int:
... return a + b
...
>>> foo(42, 101)
42101
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
80 次 |
| 最近记录: |