2016-06-09 36 views
0

我有一個模塊做的兩種東西之一:Python的設計模式

project/ 
|-- main.py 
+-- module.py 

main.py

import module 

module.do_something() 
module.set_method(module.WAY_2) 
module.do_something() 

module.py

WAY_1 = "the_first_way" 
WAY_2 = "the_second_way" 

method = WAY_1 # by default 

def set_method(new_method): 
    method = new_method 

def do_something_the_first_way(): 
    print "Doing it the first way" 

def do_something_the_second_way(): 
    print "Doing it the second way" 

def do_something(): 
    if method == WAY_1: 
     do_something_the_first_way() 
    if method == WAY_2: 
     do_something_the_second_way() 

當我跑main.py,我明白了這樣的輸出:

Doing it the first way 
Doing it the first way 

它看起來像的module.pymethod變量沒有得到更新,即使我們試圖用set_methodmain.py設置。我基於this question瞭解了這裏發生了什麼,但是我想知道解決問題的最佳方法是什麼。

什麼是最優雅的Pythonic方法來解決這個問題?

+2

'set_method'不會更改全局'method'變量,對於初學者。它並沒有真正做任何事情,截至目前 –

+0

謝謝,這幫助我解決了這個問題! – joshreesjones

回答

0

默認情況下,函數中的任何賦值都會創建一個函數局部變量;它不會以相同的名稱更新全局。您需要將其明確定義爲全局變量:

def set_method(new_method): 
    global method 
    method = new_method 
+0

謝謝!我已經解決了這個問題。 – joshreesjones