默认情况下,将参数设置为另一个参数的值。

11 浏览
0 Comments

默认情况下,将参数设置为另一个参数的值。

我曾多次见到Python程序员(包括我自己)希望在给定的函数中,如果未提供某个值,将一个变量的默认值设置为另一个变量的情况。

这是一个通过三种不同解决方案解决该问题的步骤,每个解决方案的复杂度和鲁棒性都有所提高。所以,继续往下看吧!

如果你想要做的是这样的:

def my_fun(a, b, c=a):
  return str(a) + str(b) + str(c)

在这个例子中,如果没有提供c的值,我们将在末尾追加一个str(a)。这很简单,只是一个简单的示例,我相信你的实际用例可能更加复杂。然而,这并不是符合语法规范的Python代码,它无法运行,因为a未定义。

Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'a' is not defined

然而,我经常看到的是以下答案:

- "不,这是不可能的"

- "你应该使用默认值None,然后检查该值是否为None"

如果这听起来是你遇到的问题,我希望能够帮到你!

0
0 Comments

问题出现的原因是希望在函数调用时,如果第三个参数没有提供,则将其默认值设置为第一个参数的值。然而,现有的解决方案中都存在一些问题,导致无法实现这个目标。因此,需要找到一个可以解决这个问题的方法。

解决方法分为三个部分:

Answer 1:

这个解决方法是最简单的,对于大多数情况都能起作用。代码如下:

def cast_to_string_concat(a, b, c=None):
  c = a if c is None else c
  return str(a) + str(b) + str(c)

Answer 2:

这个解决方法是使用`object()`作为占位符,代替了`None`作为第三个参数的默认值。代码如下:

_sentinel = object()
def cast_to_string_concat(a, b, c=_sentinel):
  c = a if c == _sentinel else c
  return str(a) + str(b) + str(c)

Answer 3:

这个解决方法是使用一个包装函数,使用`*args`作为参数,来处理任意数量的参数。在包装函数中,根据参数的数量来决定如何处理参数。代码如下:

def cast_to_string_append(*args):
    def string_append(a, b, c):
        # this is the original function, it is only called within the wrapper
        return str(a) + str(b) + str(c)
    if len(args) == 2:
        # if two arguments, then set the third to be the first
        return string_append(*args, args[0])
    elif len(args) == 3:
        # if three arguments, then call the function as written
        return string_append(*args)
    else:
        raise Exception(f'Function: cast_to_string_append() accepts two or three arguments, and you entered {len(args)}.')

以上三种解决方法都能解决这个问题,选择哪一种方法取决于具体的需求和情况。

0