更改python中对象的类型?

时间:2018-09-03 08:55:10

标签: python types casting

我想通过函数将类型分配给对象,例如:

def set_type(obj,dest_type):
    [change the object to the dest_type here]
    return obj

我需要这样做,因为我从文件中将参数读取为字符串,然后将它们解释为整数,浮点数和布尔值。 当然,我可以写类似

if dest_type=='bool':
    bool(obj)

但是没有更好的方法吗?像直接将类型赋予函数?

谢谢!

2 个答案:

答案 0 :(得分:1)

您可以只传递新对象的类型。
例如,

>>> def convert(v,t):
...     return t(v)


>>> a = "test"
>>> b = convert(a,list)
>>> b
['t', 'e', 's', 't']
>>> b = convert(a,bool)
>>> b
True
>>> b = convert(b,int)
>>> b
1
>>> b = convert(b,float)
>>> b
1.0

答案 1 :(得分:0)

您可以期望将函数用作if (cardTitleNow == 0) ,例如函数dest_type。在这种情况下,您的方法将变为:

bool()

示例

def set_type(obj, dest_type):
    return dest_type(obj)
相关问题