【发布时间】:2016-10-10 16:07:57
【问题描述】:
我有一个模块可以执行以下两种方式之一:
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.py 的method 变量没有得到更新,即使我们尝试使用来自main.py 的set_method 设置它。根据this question,我知道这里发生了什么,但我想知道解决问题的最佳方法是什么。
解决这个问题的最优雅的 Pythonic 方法是什么?
【问题讨论】:
-
set_method不会更改全局method变量,对于初学者来说。到目前为止,它并没有真正做任何事情 -
谢谢,帮我解决了问题!
标签: python