【发布时间】:2021-06-12 04:08:20
【问题描述】:
假设我有一个函数可以将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。
【问题讨论】:
标签: python types type-conversion