python - 简洁的整体浮动检查
问题描述
我想改进我的编码。
最近,我正在思考一些我作为 Python 构造函数的一部分编写的代码。构造函数只允许整数或整数浮点数。我想出了一些方法来检查这个,但想把它放在这里看看是否有更简洁的方法来做这个双重异常检查。
方法一: 试试,除外。
try:
if not float(x).is_integer:
raise ValueError('X must be a whole number float')
except:
raise ValueError('X must be an int or a float'):
方法2: 双if。
if not isinstance(x, (int, float)):
raise ValueError('X must be an int or whole number float.')
elif not float(x).is_integer():
raise ValueError('X must be a whole number float.')
方法 3:禁止任何非整数。
if not isinstance(x, int):
raise ValueError('X must be an int.')
我想看看最好的方法是什么。方法 3 将节省一些代码行,尽管它对代码增加了不必要的限制。方法 1 和 2 更灵活,更能反映检查的意图——为不接受输入的原因提供灵活性和透明度。
有没有更简洁的方法来执行上述检查?
提前致谢!
解决方案
有一种更紧凑的检查方式。首先考虑您要检查的是什么。你关心两件事:整数或整数浮点数。幸运的是,Python 条件是短路评估or
,and
这意味着如果其中一个条件“短路”其余条件,它们不需要评估整个条件。
您无需担心 try 中的周围事物 - 除非您首先检查它是否是 anint
或的实例float
:
In [37]: class T:
...: def __init__(self, val):
...: if not (isinstance(val, (int, float)) and float(val).is_integer()):
...: raise Exception(f'{val} must be a whole number float or integer')
...:
In [38]: T(12)
Out[38]: <__main__.T at 0x2605d2174f0>
In [39]: T(14.)
Out[39]: <__main__.T at 0x2605d1dda60>
In [40]: T('hello') # Raises exception
因为isinstance
是第一个,如果因为我传入一个字符串而没有通过,它永远不会尝试将其转换为浮点数。
推荐阅读
- javascript - JavaScript单击嵌套html中的同级
- javascript - 使用带有 react-chartjs-2 的 chartjs-chart-geo 插件实现等值线图
- ruby-on-rails - rails 6 ajax“remote:true”什么都不做
- javascript - 嵌入后获取用户输入(Discord.js)
- mysql - 使用 express 和 nodejs 插入 mysql
- sql - 使用空行和列将 Excel 工作簿导入 SQL 数据库
- java - 如何从数组列表中删除重复项
- python - 在这段代码中,有一个初始化问题导致我们的函数行为不正确。你能找到问题并解决它吗?
- c# - C#匿名类型`ToString`复杂?
- html - 如何将引号保留在引号内?