2016-05-14 51 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 
相關問題