如何将值转换为用户输入的类型?

How to convert value to user-inputted type?

假设我有一个函数可以将 8 转换为用户输入的类型:

def convert_8_to_type(to_type):

我用什么把它转换成to_type
像这样:

to_type(8)

除非我希望它正常工作(假设 to_type 不是函数)。我可以放一个大的 if ... else if ... 语句,如下所示:

if to_type == int:
    return int(8)
else if to_type == float:
    return float(8)
else if to_type == Decimal:
    return Decimal(8)
else if to_type == str:
    return str(8)
else if to_type == bool:
    return bool(8)
else if to_type == bytes:
    return bytes(8)

但是如果用户试图转换为我在转换中明确提供的类型怎么办 table?最有效的可能是简单地使用 return(在这种情况下)8.

to_type 确实是一个函数,如果这是调用者传入的:

def convert_8_to_type(to_type):
   return to_type(8)
>>> print(convert_8_to_type(bytes))
b'\x00\x00\x00\x00\x00\x00\x00\x00'

从命名类型的 str 中派生类型完全是另一个问题,但是从您的代码示例来看,您似乎正在获取实际类型,而不是它作为字符串的名称(例如,您有to_type == int,而不是 to_type == 'int'),所以这应该“正常工作”。