【问题标题】:Pass a default value to a function before a required value在所需值之前将默认值传递给函数
【发布时间】:2016-05-14 15:40:28
【问题描述】:

我正在尝试编写一个程序来查找某个范围内的素数。我正在尝试做的一件事是允许在没有所有参数的情况下调用该函数。

我想做的是这样的:

def find_primes(start=1, stop, primes=None):

primes 变量将被初始化为一个空白列表(我正在尝试使程序递归)。

但是,这会导致错误,因为我不能在所有必需值之前为参数使用默认值。

我想到的一种方法是:

def find_primes(start, stop=-1, primes=None):
    if primes is None:
        primes = []
    if stop = -1:
        stop = start
        start = 1

基本上,如果 stop 保持在其默认的超出范围的值,我可以翻转变量。然而,这似乎很老套,我希望有更好的方法来做到这一点。

我知道这个实现的一个例子是 range 函数,因为我可以把它称为

range(stop)

range(start, stop[, step])

这可以实现吗?提前致谢。

编辑:在其他语言中,我可以使用函数重载:

def find_primes(stop):
    return find_primes(1, stop)
def find_primes(start, stop, primes=None)
    #Code

这在 Python 中存在吗?

【问题讨论】:

标签: python-3.x


【解决方案1】:

Range 是一个内置函数,但如果它是用 Python 实现的,它可能会使用与您建议的相同的“Hack”。由于 Python 没有 C-/Java 风格的函数重载,因此“Hack”确实是在没有 *args 的情况下在 Python 中实现此目的的唯一方法,并且当您使用 None 作为默认值(而不是任意的 @ 987654323@) 它甚至可以被认为是惯用的:

def find_primes(start_or_stop, stop_or_none=None, primes=None):
    """
    find_primes([start], stop, [primes])
    """
    # ^ Communicate the semantics of the signature by the docstring,
    # like `range` does.   
    if primes is None:
        primes = []
    if stop_or_none is None:
        start, stop = 1, start_or_stop
    else:
        start, stop = start_or_stop, stop_or_none

【讨论】:

    猜你喜欢
    • 2015-01-11
    • 1970-01-01
    • 2014-10-24
    • 2012-03-23
    • 1970-01-01
    • 2015-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多