python 以类型作为参数来转换变量

Joh*_*Jos 4 python types casting

是否有一个转换函数可以同时转换变量和类型?例如:

cast_var = cast_fn(original_var, type_to_cast_to)
Run Code Online (Sandbox Code Playgroud)

我想用它作为一种有效的方法来循环从字符串解析的输入参数列表,有些需要转换为 int、bool、float 等......

che*_*ner 6

所有 Python 类型都是可调用的

new_val = int(old_val)
Run Code Online (Sandbox Code Playgroud)

所以不需要特殊的函数。事实上,您所要求的实际上只是一个apply功能

new_val = apply(int, old_val)
Run Code Online (Sandbox Code Playgroud)

它存在于 Python 2 中,但从 Python 3 中删除,因为它从来没有必要;任何可以作为第一个参数传递的表达式apply始终可以与调用“operator”一起使用:

apply(expr, *args) == expr(*args)
Run Code Online (Sandbox Code Playgroud)