python - 如何将值转换为用户输入的类型?
问题描述
假设我有一个函数可以转换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。
解决方案
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'
),所以这应该“正常工作”。
推荐阅读
- mysql - 有什么方法可以使用 mysql 在 ssh 上对用户进行身份验证?
- facebook - 营销 API - 缺少系统用户权限,使用开发层
- javascript - 如何使用 bootstrap-datetime-picker-for-rails gem 以 UTC 格式而不是本地时间显示日期选择器
- redhat - Red Hat 8 vpn 客户端无法连接到路由器 ac5300 上的 OpenVPN 服务器
- javascript - plotly javascript scatter更新数据
- javascript - 在鼠标悬停期间替换部分 URL 以获得原始大小的图像
- r - 如何使用 R 从共享点文件夹下载文件
- bash - Add multiple commands in single alias
- mysql - 如何创建 API 以在 MySQL 中插入数据,并使用重复键传递 json
- postgresql - PostgreSQL 语法错误我不明白