0

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

像一些示例代码:

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
4

1 回答 1

2

globals()返回 adict以便您可以使用以下方法分配新值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

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

于 2016-12-04T14:12:29.630 回答