2016-02-29 30 views
0

我在做一個編碼練習,其中一個測試調用下面定義的方法get_count()。其中一個測試調用get_count()而不傳遞任何參數。我希望函數仍然返回result = {'vowels':0, 'consonants':0},即使函數沒有任何參數被調用。有沒有辦法在Python中做到這一點?處理不帶參數調用函數的情況?

def get_count(words): 
    result = {'vowels':0, 'consonants':0} 
    if not words: 
     return result 
    if type(words) is not str: 
     return result 
    for letter in words.lower(): 
     if letter in 'aeiou': 
      result['vowels'] += 1 
     elif letter.isalpha(): 
      result['consonants'] += 1 
    return result 

回答

1

是,使用默認參數:

def get_count(words=None): 
    result = {'vowels':0, 'consonants':0} 
    if not words: 
     return result 
    if type(words) is not str: 
     return result 
    for letter in words.lower(): 
     if letter in 'aeiou': 
      result['vowels'] += 1 
     elif letter.isalpha(): 
      result['consonants'] += 1 
    return result 

方便的是,你已經在那裏有一個if not wordsNone的布爾值爲False,因此如果沒有給出words,那麼if語句將被執行。

3

這是你要使用default function argument的地方。

def get_count(words=None): 
    result = {'vowels':0, 'consonants':0} 
    if not words: 
     return result 
    if type(words) is not str: 
     return result 
    for letter in words.lower(): 
     if letter in 'aeiou': 
      result['vowels'] += 1 
     elif letter.isalpha(): 
      result['consonants'] += 1 
    return result 

通常對於只想返回默認結果的情況,您希望使用None作爲默認值。在你的函數可以在沒有傳遞參數的情況下運行的情況下,你可以使用任何你想要的值作爲默認值。只要注意使用可變對象作爲值,因爲它可能會產生一些有趣的結果。具體而言,該對象僅在函數第一次定義時創建,因此每次調用該函數時都會持續。

下面是一個例子:

def mutable(x, y=[]): 
    y.append(x) 
    return y 

print(mutable(1)) # Prints [1] 
print(mutable(2)) # Prints [1, 2] 
+0

我最喜歡使用默認值時不想要的行爲的例子是這裏列出的第一個「面試問題」:https://www.toptal.com/python/interview-questions – jdogg

0

鑑於words是一個字符串,你可以使用空字符串的默認參數'',那麼你可以簡化你的代碼。 BTW python中常見的成語是EAFP一般用於LBFL代替:

def get_count(words=''): 
    result = {'vowels':0, 'consonants':0} 
    try: 
     for letter in words.lower(): 
      if letter in 'aeiou': 
       result['vowels'] += 1 
      elif letter.isalpha(): 
       result['consonants'] += 1 
    except AttributeError: 
     pass 
    return result 

如果你想完全過工程師就可以使用partitionitertools配方:

import itertools as it 

def partition(pred, iterable): 
    t1, t2 = it.tee(iterable) 
    return filter(pred, t1), it.filterfalse(pred, t2) 

def get_count(words=''): 
    p = partition(lambda c: c in 'aeiou', filter(str.isalpha, words.lower())) 
    return {k: sum(1 for _ in v) for k, v in zip(['vowels', 'consonants'], p)} 

>>> get_count('Hello, World!') 
{'consonants': 7, 'vowels': 3} 

對不起我很無聊