2014-05-14 74 views
0

請原諒我這個可憐的頭銜,我真的不知道如何將我的問題寫成一個好題目。請編輯它,如果你想。這裏的問題是:Python函數結構(設計)混淆

我碰到這段代碼傳來:

def main(): 
    info = [] # not used anywhere else other than inside parse_file_info() 
    file_path = '/some/file/path' 
    # .... 
    parse_file_info(file_path, info) 

def parse_file_info(file_path, info): 
    # join lines according to condition 
    # append joined lines to info along the run 
    with open(file_path) as f: 
     lines = f.readlines() 
    insert = '' 
    brace_count = 0 
    for line in lines: 
     brace_count += line.count('{') 
     brace_count -= line.count('}') 
     insert = insert + line 
     if brace_count == 0: 
      info.append(insert) 
      insert = '' 

起初,我甚至不認爲這工作(還是新的Python),然後我做了一些研究,發現this

現在我知道這個方法有效,我不太喜歡它,我不知道這是否是一種好的做法。我反而會寫的代碼會是這樣的:

def main(): 
    file_path = '/some/file/path' 
    # ..... 
    info = parse_file_info(file_path) 

def parse_file_info(file_path): 
    # join lines according to some condition 
    # return a list of joined lines 
    with open(file_path) as f: 
     lines = f.readlines() 
    insert = '' 
    mylist = [] 
    brace_count = 0 
    for line in lines: 
     brace_count += line.count('{') 
     brace_count -= line.count('}') 
     insert = insert + line 
     if brace_count == 0: 
      mylist.append(insert) 
      insert = '' 
    return mylist 

請告訴我哪一個是一個更好的做法,爲什麼

+2

這個問題不適合SO,因爲它主要是基於意見的。然而,Pythonic最佳實踐的標準來源是[PEP-0008](http://legacy.python.org/dev/peps/pep-0008/)和[PEP-0020](http://legacy.python。組織/開發/ PEPS/PEP-0020 /)。這些狀態中的後者*「顯式優於隱式」*,在此基礎上,我傾向於選項2.另請參見[此處](http://docs.python-guide.org/en/latest/writing /結構/#面向對象編程):*「...建議儘可能少地使用函數和過程......副作用」。* – jonrsharpe

+1

PS:'brace_count'在兩個片段中的賦值之前被引用。 –

+0

@jonrsharpe謝謝,這是我正在尋找的實際答案,不知道在哪裏可以找到信息 – user1948847

回答

0

因此這個問題已經被確定爲主要的意見爲主,我會留第二種解決方案,因爲它明確地告訴程序員的意圖是什麼。

在某個地方定義某些東西並在另一個地方修改它會讓你在某個時候看到兩者。現在想象那兩個地方是在不同的模塊/包中。