在python中更改对象的类型?

问题描述 投票:0回答:2

我想通过函数为对象分配一个类型,如:

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

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

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

但是没有更好的方法吗?喜欢直接给函数类型?

谢谢!

python types casting
2个回答
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

0
投票

你可以期待一个函数dest_type,例如功能bool()。在这种情况下,您的方法将变为:

def set_type(obj, dest_type):
    return dest_type(obj)

obj = 1
set_type(obj, bool) # Yields True
© www.soinside.com 2019 - 2024. All rights reserved.