简体   繁体   English

python将类型作为参数的变量转换

[英]python casting variables with type as argument

Is there a casting function which takes both the variable and type to cast to?是否有一个强制转换函数可以同时转换变量和类型? Such as:比如:

cast_var = cast_fn(original_var, type_to_cast_to)

I want to use it as an efficient way to cycle through a list of input parameters parsed from a string, some will need to be cast as int, bool, float etc...我想将它用作循环遍历从字符串解析的输入参数列表的有效方法,有些需要转换为 int、bool、float 等...

All Python types are callable所有 Python 类型都是可调用的

new_val = int(old_val)

so no special function is needed.所以不需要特殊功能。 Indeed, what you are asking for is effectively just an apply function实际上,您所要求的实际上只是一个apply功能

new_val = apply(int, old_val)

which exists in Python 2, but was removed from Python 3 as it was never necessary;它存在于 Python 2 中,但从 Python 3 中删除,因为它从来没有必要; any expression that could be passed as the first argument to apply can always be used with the call "operator":任何可以作为第一个参数传递给apply表达式都可以与调用“operator”一起使用:

apply(expr, *args) == expr(*args)

Short answer: This works:简短回答:这有效:

>>> t = int
>>> s = "9"
>>> t(s)

Or a full example:或者一个完整的例子:

def convert(type_id, value):
    return type_id(value)

convert(int, "3")  # --> 3
convert(str, 3.0)  # --> '3.0'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM