我想通过函数为对象分配一个类型,如:
def set_type(obj,dest_type):
[change the object to the dest_type here]
return obj
我需要这样做是因为我将文件中的参数作为字符串读取,然后将它们解释为整数,浮点数和布尔值。当然,我可以写类似的东西
if dest_type=='bool':
bool(obj)
但是没有更好的方法吗?喜欢直接给函数类型?
谢谢!
您可以只传递新对象的类型。 例如,
>>> 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
你可以期待一个函数dest_type
,例如功能bool()
。在这种情况下,您的方法将变为:
def set_type(obj, dest_type):
return dest_type(obj)
例
obj = 1
set_type(obj, bool) # Yields True