【问题标题】:How to convert value to user-inputted type?如何将值转换为用户输入的类型?
【发布时间】: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


    【解决方案1】:

    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'),所以这应该“正常工作”。

    【讨论】:

    • 我没有意识到当我输入这些类型时,它会作为函数输入,或者它们可以这样运行。
    • 在确定它不起作用之前,请始终尝试至少运行一次您的代码! :)
    • @CATboardBETA 如果您将用户输入字符串转换为类型构造函数,您需要做很多额外的工作。请参阅我的答案以了解另一种方法。您接受的答案仍然需要一个大的if 分支,并且仍然需要您处理不受支持的转换。
    • @blorgon 它实际上可以很好地处理不支持的类型转换。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多