Python 如何将值转换为用户输入的类型?
假设我有一个函数,它将Python 如何将值转换为用户输入的类型?,python,types,type-conversion,Python,Types,Type Conversion,假设我有一个函数,它将8转换为用户输入的类型: def convert_8_to_type(to_type): 如何将其转换为类型? 大概是这样的: to_type(8) 除非我希望它能正常工作(给定to_type不是一个函数)。如果。。。else if…语句,如下所示: if to_type == int: return int(8) else if to_type == float: return float(8) else if to_type == Decimal:
8
转换为用户输入的类型:
def convert_8_to_type(to_type):
如何将其转换为类型?
大概是这样的:
to_type(8)
除非我希望它能正常工作(给定to_type
不是一个函数)。如果。。。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。
to_type
确实是一个函数,如果调用方传入的是:
def convert_8_to_type(to_type):
return to_type(8)
从命名类型的
str
派生类型完全是另一个问题,但从代码示例来看,您得到的是实际类型,而不是字符串形式的名称(例如,您有to_type==int
,而不是to_type==int'
),因此这应该“正常工作”.我没有意识到,当我输入这些类型时,它会作为函数输入,或者它们可以这样运行。在确定代码不起作用之前,请始终尝试至少运行一次代码!:)@CATboardBETA如果要将用户输入字符串转换为类型构造函数,则需要做大量额外的工作。请参阅我的答案,以了解另一种方法。您接受的答案仍然需要一个大的if
分支,并且仍然需要您处理不支持的转换。@blorgon它实际上可以很好地处理不支持的类型转换。
>>> print(convert_8_to_type(bytes))
b'\x00\x00\x00\x00\x00\x00\x00\x00'