python - 检测存在哪些可选参数的 Pythonic 方法
问题描述
对python来说还是相当新的。
我想知道什么是检测 python 程序选择的输出响应的好方法。
例如,如果您要制作一个速度/距离/时间计算器,如果只给出了 2 个输入,您将如何检测哪个是丢失的输入以及输出?我可以想到一些相当粗略的方法,但我想知道如果更复杂的任务要发挥作用,是否还有其他方法。
我猜是这样的:
def sdf(speed=0, distance=0, time=0):
# detect which parameter has no input / equals 0
# calculate result
# return result
sdf(speed=10, distance=2)
有任何想法吗?
解决方案
Python 允许您动态更改变量的类型。由于您正在使用整数并且0
可能是计算中的有用值,因此您的默认“不存在”值应该是None
:
def sdf(speed=None, time=None, distance=None):
if speed is None:
return calculate_speed(time, distance), time, distance
if time is None:
return speed, calculate_time(speed, distance), distance
if distance is None:
return speed, time, calculate_distance(speed, time)
# All paramters have been set! Maybe check if all three are correct
return speed, time, distance
speed, time, distance = sdf(speed=1, distance=2)
这样你就不必知道后来发生了什么。这个函数会给你所有三个值,假设你给了它至少 3 个值中的 2 个。
如果您的程序流程允许多个值 be None
,则您的函数calculate_XY
在检测到异常时应该抛出异常。所以在这种情况下:
def calculate_distance(speed, time)
return speed * time
它会抛出一个不受支持的操作数异常(TypeError),所以不需要用无用的断言来混乱你的代码。
如果您真的不知道要设置多少个参数,请执行以下操作:
try:
retval = sdf(None, None, x)
except TypeError as e:
print(e)
handle_exception(e)
另外提醒一下:is
Python 中的运算符检查对象是否是同一个对象,而不是它们的值。由于分配给None
的对象只是“指向全局对象的指针”(简化) ,因此首选None
检查值是否“包含” 。但是请注意:None
is
a = b = list()
a is b
True
# a and b are 'pointers' to the same list object
a = list()
b = list()
a is b
False
a == b
True
# a and b contain 2 different list objects, but their contents are identical
请注意,要比较值使用==
并检查它们是否是同一个对象,请使用is
.
高温高压
推荐阅读
- xaml - xamarin 表单 - 列表视图 - 选择器 - 不会与列表视图中的行对齐
- mysql-8.0 - 是否可以将 mysql 从 8.0.24 回滚到 8.0.23?
- java - 使用 Java Streams 将字符串拆分为 Map
- python - 为什么当我尝试使用 virtualenv 时它不起作用?
- google-maps - Polygon 上的 GoogleMap dragend 事件会破坏 Material Angular Snackbar
- java - JXMapViewer (openstreetmap) Drow Directions between 2 point
- javascript - Postman GET url 请求测试,用于简单的服务器 API
- checkbox - 为什么 JQuery Mobile 无法选中该复选框?
- javascript - Jquery ui 菜单问题
- python - 无法访问 jinja 模板中的 ansible 字典项