首页 > 解决方案 > 检测存在哪些可选参数的 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)

有任何想法吗?

标签: pythonpython-3.x

解决方案


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)

另外提醒一下:isPython 中的运算符检查对象是否是同一个对象,而不是它们的值。由于分配给None的对象只是“指向全局对象的指针”(简化) ,因此首选None检查值是否“包含” 。但是请注意:Noneis

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.

高温高压


推荐阅读