【问题标题】:Python design patternPython 设计模式
【发布时间】:2016-10-10 16:07:57
【问题描述】:

我有一个模块可以执行以下两种方式之一:

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

ma​​in.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 变量没有得到更新,即使我们尝试使用来自main.pyset_method 设置它。根据this question,我知道这里发生了什么,但我想知道解决问题的最佳方法是什么。

解决这个问题的最优雅的 Pythonic 方法是什么?

【问题讨论】:

  • set_method 不会更改全局 method 变量,对于初学者来说。到目前为止,它并没有真正做任何事情
  • 谢谢,帮我解决了问题!

标签: python


【解决方案1】:

默认情况下,函数中的任何赋值都会创建一个函数局部变量;它不会更新同名的全局变量。您需要将其明确定义为全局:

def set_method(new_method):
    global method
    method = new_method

【讨论】:

  • 谢谢!我已经解决了这个问题。
猜你喜欢
  • 2010-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-22
  • 1970-01-01
  • 2010-12-31
  • 1970-01-01
  • 2022-10-08
相关资源
最近更新 更多