在 class 中使用全局变量时,它不会 return 模块级全局变量,而是只会出错

When using globals in a class it does not return module level globals instead it will just Error

当使用内置 globals() 函数时,它似乎是这样做的:当我尝试访问我设置为从 class 中更改的全局值时(不是 class全局,因为它会在每次初始化时被覆盖。无论 class 有多少次初始化,我所做的全局都应该被保留和使用。

像一些示例代码:

somevalue = False

class SomeClass(object):
    """
    ...
    """
    def __init__(self):
        self.change_global_value()

    def change_global_value(self):
        """
        Changes global module values that this class is in.
        """
        globals().somevalue = True  # Error. (line 14)
        self.__module__.globals().somevalue = True  # Error. (line 14, after some changes)
        somevalue = True  # Error as well. (line 14, after some more changes)

发生的回溯:

Traceback (most recent call last):
  File "<stdin>", line 14, in <module>
    globals().somevalue = True  # Error.
AttributeError: 'dict' object has no attribute 'somevalue'

Traceback (most recent call last):
  File "<stdin>", line 14, in <module>
    self.__module__.globals().somevalue = True  # Error.
AttributeError: 'str' object has no attribute 'globals'

Traceback (most recent call last):
  File "<stdin>", line 14, in change_global_value
    somevalue = True  # Error as well.
UnboundLocalError: local variable 'somevalue' referenced before assignment

globals() returns a dict 因此您可以使用 globals()['somevalue'] = 'newvalue':

分配新值
somevalue = False

class SomeClass(object):
    """
    ...
    """
    def __init__(self):
        self.change_global_value()

    def change_global_value(self):
        """
        Changes global module values that this class is in.
        """
        globals()['somevalue'] = True

首选形式只是将变量定义为全局变量:

somevalue = False

class SomeClass(object):
    """
    ...
    """
    def __init__(self):
        self.change_global_value()

    def change_global_value(self):
        """
        Changes global module values that this class is in.
        """
        global somevalue
        somevalue = True

请注意,在一般情况下,尤其是在 类 中,这通常是一种不好的做法。