【问题标题】:Is there a more simple way to change and use global variables?有没有更简单的方法来改变和使用全局变量?
【发布时间】:2015-01-20 08:28:51
【问题描述】:

如果您在函数之前声明一个全局变量并尝试在函数中更改该变量,则会引发错误:

james = 100

def runthis():
    james += 5

这行不通。

除非你在函数中再次声明全局变量,像这样:

james = 100

def runthis():
    global james
    james += 5

有没有更简单的方法来改变函数内部的变量?一次又一次地重新声明变量有点混乱和烦人。

【问题讨论】:

  • global x 似乎是一种将变量声明为全局变量的非常简单的方法。你会如何想象一个更简单的方法会是什么样子?也就是说,全局变量应该很少需要。我几乎从不使用global 键盘。
  • 您可以将james 引用为globals()['james']
  • Sven Mrnach,在我需要这种帮助的情况下,我发现自己不得不不断更改多个函数中的全局变量,这有点痛苦。
  • @user3579419 好吧,我的意思是——不要那样做。全局状态是邪恶的,使用大量全局状态会导致无法维护和无法测试的代码。这一点在这里用几个 cmet 来解释有点困难,但这是每个有经验的程序员都可以确认的。
  • 如果它可以阻止使用全局变量,那就更好了。

标签: python global-variables


【解决方案1】:

在函数中避免使用全局变量不是更简单吗?

james = 100

def runthis(value):
    return value + 5

james = runthis(james)

如果您有很多它们,将它们放在一个可变容器中可能更有意义,例如字典:

def runthis(scores):
    scores['james'] += 5

players = {'james': 100, 'sue': 42}

runthis(players)
print players  # -> {'james': 105, 'sue': 42}

如果您不喜欢 scores['james'] 表示法,您可以创建一个专门的 dict 类:

# from http://stackoverflow.com/a/15109345/355230
class AttrDict(dict):
    def __init__(self, *args, **kwargs):
        super(AttrDict, self).__init__(*args, **kwargs)
        self.__dict__ = self

def runthis(scores):
    scores.james += 5  # note use of dot + attribute name

players = AttrDict({'james': 100, 'sue': 42})

runthis(players)
print players  # -> {'james': 105, 'sue': 42}

【讨论】:

  • 是的,但是在我处理大量代码的情况下,将这么多参数放入一个函数中可能会变得混乱。
【解决方案2】:

在 Python 中修改全局变量很难看。如果需要维护状态,请使用class

class MyClass(object):
    def __init__(self):
        self.james = 100
    def runThis(self):
        self.james += 5

或者,如果您需要在所有实例之间共享james,请将其设为类属性:

class MyClass(object):
    james = 100
    def runThis(self):
        MyClass.james += 5

它可能不会更简单,但肯定更 Pythonic。

【讨论】:

  • 天才,我从未真正想到过,但它是一个很好的解决方案。所以谢谢:D
  • 很高兴您对课堂解决方案感到满意。对于其他人,实际上,最好不要使用全局变量。请参阅下面的@martineau。
猜你喜欢
  • 1970-01-01
  • 2010-09-19
  • 1970-01-01
  • 2015-08-30
  • 1970-01-01
  • 2013-09-25
  • 2018-03-07
  • 2021-10-07
  • 2019-02-08
相关资源
最近更新 更多