首页 > 解决方案 > 如何将值转换为用户输入的类型?

问题描述

假设我有一个函数可以转换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)

但是,如果用户尝试转换为我在转换表中明确提供的类型怎么办?最有效的可能是让它简单地返回(在这种情况下)8。

标签: pythontypestype-conversion

解决方案


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命名类型的 a 派生类型完全是另一个问题,但是从您的代码示例看来,您获得的是实际类型,而不是字符串的名称(例如,您有to_type == int,不是to_type == 'int'),所以这应该“正常工作”。


推荐阅读