2016-05-14 50 views
0

我正在尝试编写一个程序来查找某个范围内的素数。我试图做的事情之一是允许函数在没有所有参数的情况下被调用。在需要的值之前传递一个默认值到一个函数

我想要做的是这样的:

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

素数则变量将被初始化为空的列表(我想使程序递归)。

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

一种方式我觉得这样做的是:

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

基本上,我可以翻转的变量,如果停止维持在默认值,超出范围的值。然而,这看起来很不方便,我希望有更好的方法来做到这一点。

某处的一个例子,我知道这是实现在范围功能,因为我可以把它作为

range(stop) 

range(start, stop[, step]) 

这是可能实现?提前致谢。

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

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

这是否存在使用Python?

+0

的可能的复制http://stackoverflow.com/questions/13366293/how-can-the-built-in-range-function-take-a-single-argument-or-three – jonrsharpe

+0

噢。谢谢。在发布之前搜索解决方案时,我应该更一般。 * args方法肯定会起作用。 – ratorx

回答

0

Range是一个内置函数,但如果它是用Python实现的,它可能会使用与您所建议的相同的“Hack”。由于Python没有C/Java风格的函数重载,这个“Hack”确实是在没有*args的Python中实现这个功能的唯一方法,并且当你使用None作为默认值(而不是任意的-1)时,甚至可能被认为是地道:

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 
相关问题