如何在Python中访问类内部的全局变量

时间:2022-09-06 13:52:10

I have this:

我有这个:

g_c = 0

class TestClass():
    global g_c
    def run(self):
        for i in range(10):
            g_c = 1
            print g_c

t = TestClass()
t.run()

print g_c

how can I actually modify my global variable g_c?

我怎样才能真正修改我的全局变量g_c?

5 个解决方案

#1


69  

By declaring it global inside the function that accesses it:

通过在访问它的函数内声明它是全局的:

g_c = 0

class TestClass():
    def run(self):
        global g_c
        for i in range(10):
            g_c = 1
            print g_c

The Python documentation says this, about the global statement:

Python文档说明了这一点,关于全局声明:

The global statement is a declaration which holds for the entire current code block.

全局语句是一个声明,它适用于整个当前代码块。

#2


10  

You need to move the global declaration inside your function:

您需要在函数内移动全局声明:

class TestClass():
    def run(self):
        global g_c
        for i in range(10):
            g_c = 1
            print g_c

#3


3  

I understand using a global variable is sometimes the most convenient thing to do, especially in cases where usage of class makes the easiest thing so much harder (e.g., multiprocessing). I ran into the same problem with declaring global variables and figured it out with some experiments.

我理解使用全局变量有时候是最方便的事情,特别是在使用类使得最简单的事情变得如此困难的情况下(例如,多处理)。我在声明全局变量时遇到了同样的问题,并通过一些实验得出结论。

The reason that g_c was not changed by the run function within your class is that the referencing to the global name within g_c was not established precisely within the function. The way Python handles global declaration is in fact quite tricky. The command global g_c has two effects:

g_c未被类中的run函数更改的原因是g_c中对全局名称的引用未在函数内精确建立。 Python处理全局声明的方式实际上非常棘手。命令global g_c有两个效果:

  1. Preconditions the entrance of the key "g_c" into the dictionary accessible by the built-in function, globals(). However, the key will not appear in the dictionary until after a value is assigned to it.

    预先设置密钥“g_c”进入可由内置函数globals()访问的字典中。但是,在为其分配值之前,密钥不会出现在字典中。

  2. (Potentially) alters the way Python looks for the variable g_c within the current method.

    (可能)改变Python在当前方法中查找变量g_c的方式。

The full understanding of (2) is particularly complex. First of all, it only potentially alters, because if no assignment to the name g_c occurs within the method, then Python defaults to searching for it among the globals(). This is actually a fairly common thing, as is the case of referencing within a method modules that are imported all the way at the beginning of the code.

对(2)的充分理解特别复杂。首先,它只会改变,因为如果在方法中没有对名称g_c进行赋值,那么Python默认在globals()中搜索它。这实际上是一个相当普遍的事情,就像在代码开头一直导入的方法模块中引用一样。

However, if an assignment command occurs anywhere within the method, Python defaults to finding the name g_c within local variables. This is true even when a referencing occurs before an actual assignment, which will lead to the classic error:

但是,如果赋值命令出现在方法中的任何位置,则Python默认在局部变量中查找名称g_c。即使在实际分配之前发生引用也是如此,这将导致经典错误:

UnboundLocalError: local variable 'g_c' referenced before assignment

Now, if the declaration global g_c occurs anywhere within the method, even after any referencing or assignment, then Python defaults to finding the name g_c within global variables. However, if you are feeling experimentative and place the declaration after a reference, you will be rewarded with a warning:

现在,如果声明全局g_c出现在方法中的任何位置,即使在任何引用或赋值之后,Python也默认在全局变量中找到名称g_c。但是,如果您感觉有实验性并在引用后放置声明,您将收到警告:

SyntaxWarning: name 'g_c' is used prior to global declaration

If you think about it, the way the global declaration works in Python is clearly woven into and consistent with how Python normally works. It's just when you actually want a global variable to work, the norm becomes annoying.

如果你考虑一下,全局声明在Python中的工作方式显然与Python通常的工作原理相一致。只是当你真正想要一个全局变量工作时,规范变得烦人。

Here is a code that summarizes what I just said (with a few more observations):

这是一个代码,总结了我刚才所说的内容(还有一些观察结果):

g_c = 0
print ("Initial value of g_c: " + str(g_c))
print("Variable defined outside of method automatically global? "
      + str("g_c" in globals()))

class TestClass():
    def direct_print(self):
        print("Directly printing g_c without declaration or modification: "
              + str(g_c))
        #Without any local reference to the name
        #Python defaults to search for the variable in globals()
        #This of course happens for all the module names you import

    def mod_without_dec(self):
        g_c = 1
        #A local assignment without declaring reference to global variable
        #makes Python default to access local name
        print ("After mod_without_dec, local g_c=" + str(g_c))
        print ("After mod_without_dec, global g_c=" + str(globals()["g_c"]))


    def mod_with_late_dec(self):
        g_c = 2
        #Even with a late declaration, the global variable is accessed
        #However, a syntax warning will be issued
        global g_c
        print ("After mod_with_late_dec, local g_c=" + str(g_c))
        print ("After mod_with_late_dec, global g_c=" + str(globals()["g_c"]))

    def mod_without_dec_error(self):
        try:
            print("This is g_c" + str(g_c))
        except:
            print("Error occured while accessing g_c")
            #If you try to access g_c without declaring it global
            #but within the method you also alter it at some point
            #then Python will not search for the name in globals()
            #!!!!!Even if the assignment command occurs later!!!!!
        g_c = 3

    def sound_practice(self):
        global g_c
        #With correct declaration within the method
        #The local name g_c becomes an alias for globals()["g_c"]
        g_c = 4
        print("In sound_practice, the name g_c points to: " + str(g_c))


t = TestClass()
t.direct_print()
t.mod_without_dec()
t.mod_with_late_dec()
t.mod_without_dec_error()
t.sound_practice()

#4


1  

class flag:
    ## Store pseudo-global variables here

    keys=False

    sword=True

    torch=False


## test the flag class

print('______________________')

print(flag.keys)
print(flag.sword)
print (flag.torch)


## now change the variables

flag.keys=True
flag.sword= not flag.sword
flag.torch=True

print('______________________')

print(flag.keys)
print(flag.sword)
print (flag.torch)

#5


0  

Its very simple to make variable as a global in side the class, we can use this global variable in any other functions inside the class as well

将变量作为类的全局变量非常简单,我们也可以在类中的任何其他函数中使用这个全局变量

a = 0

a = 0

class b(): global a a = 10

class b():global a a = 10

a 10

一个10

#1


69  

By declaring it global inside the function that accesses it:

通过在访问它的函数内声明它是全局的:

g_c = 0

class TestClass():
    def run(self):
        global g_c
        for i in range(10):
            g_c = 1
            print g_c

The Python documentation says this, about the global statement:

Python文档说明了这一点,关于全局声明:

The global statement is a declaration which holds for the entire current code block.

全局语句是一个声明,它适用于整个当前代码块。

#2


10  

You need to move the global declaration inside your function:

您需要在函数内移动全局声明:

class TestClass():
    def run(self):
        global g_c
        for i in range(10):
            g_c = 1
            print g_c

#3


3  

I understand using a global variable is sometimes the most convenient thing to do, especially in cases where usage of class makes the easiest thing so much harder (e.g., multiprocessing). I ran into the same problem with declaring global variables and figured it out with some experiments.

我理解使用全局变量有时候是最方便的事情,特别是在使用类使得最简单的事情变得如此困难的情况下(例如,多处理)。我在声明全局变量时遇到了同样的问题,并通过一些实验得出结论。

The reason that g_c was not changed by the run function within your class is that the referencing to the global name within g_c was not established precisely within the function. The way Python handles global declaration is in fact quite tricky. The command global g_c has two effects:

g_c未被类中的run函数更改的原因是g_c中对全局名称的引用未在函数内精确建立。 Python处理全局声明的方式实际上非常棘手。命令global g_c有两个效果:

  1. Preconditions the entrance of the key "g_c" into the dictionary accessible by the built-in function, globals(). However, the key will not appear in the dictionary until after a value is assigned to it.

    预先设置密钥“g_c”进入可由内置函数globals()访问的字典中。但是,在为其分配值之前,密钥不会出现在字典中。

  2. (Potentially) alters the way Python looks for the variable g_c within the current method.

    (可能)改变Python在当前方法中查找变量g_c的方式。

The full understanding of (2) is particularly complex. First of all, it only potentially alters, because if no assignment to the name g_c occurs within the method, then Python defaults to searching for it among the globals(). This is actually a fairly common thing, as is the case of referencing within a method modules that are imported all the way at the beginning of the code.

对(2)的充分理解特别复杂。首先,它只会改变,因为如果在方法中没有对名称g_c进行赋值,那么Python默认在globals()中搜索它。这实际上是一个相当普遍的事情,就像在代码开头一直导入的方法模块中引用一样。

However, if an assignment command occurs anywhere within the method, Python defaults to finding the name g_c within local variables. This is true even when a referencing occurs before an actual assignment, which will lead to the classic error:

但是,如果赋值命令出现在方法中的任何位置,则Python默认在局部变量中查找名称g_c。即使在实际分配之前发生引用也是如此,这将导致经典错误:

UnboundLocalError: local variable 'g_c' referenced before assignment

Now, if the declaration global g_c occurs anywhere within the method, even after any referencing or assignment, then Python defaults to finding the name g_c within global variables. However, if you are feeling experimentative and place the declaration after a reference, you will be rewarded with a warning:

现在,如果声明全局g_c出现在方法中的任何位置,即使在任何引用或赋值之后,Python也默认在全局变量中找到名称g_c。但是,如果您感觉有实验性并在引用后放置声明,您将收到警告:

SyntaxWarning: name 'g_c' is used prior to global declaration

If you think about it, the way the global declaration works in Python is clearly woven into and consistent with how Python normally works. It's just when you actually want a global variable to work, the norm becomes annoying.

如果你考虑一下,全局声明在Python中的工作方式显然与Python通常的工作原理相一致。只是当你真正想要一个全局变量工作时,规范变得烦人。

Here is a code that summarizes what I just said (with a few more observations):

这是一个代码,总结了我刚才所说的内容(还有一些观察结果):

g_c = 0
print ("Initial value of g_c: " + str(g_c))
print("Variable defined outside of method automatically global? "
      + str("g_c" in globals()))

class TestClass():
    def direct_print(self):
        print("Directly printing g_c without declaration or modification: "
              + str(g_c))
        #Without any local reference to the name
        #Python defaults to search for the variable in globals()
        #This of course happens for all the module names you import

    def mod_without_dec(self):
        g_c = 1
        #A local assignment without declaring reference to global variable
        #makes Python default to access local name
        print ("After mod_without_dec, local g_c=" + str(g_c))
        print ("After mod_without_dec, global g_c=" + str(globals()["g_c"]))


    def mod_with_late_dec(self):
        g_c = 2
        #Even with a late declaration, the global variable is accessed
        #However, a syntax warning will be issued
        global g_c
        print ("After mod_with_late_dec, local g_c=" + str(g_c))
        print ("After mod_with_late_dec, global g_c=" + str(globals()["g_c"]))

    def mod_without_dec_error(self):
        try:
            print("This is g_c" + str(g_c))
        except:
            print("Error occured while accessing g_c")
            #If you try to access g_c without declaring it global
            #but within the method you also alter it at some point
            #then Python will not search for the name in globals()
            #!!!!!Even if the assignment command occurs later!!!!!
        g_c = 3

    def sound_practice(self):
        global g_c
        #With correct declaration within the method
        #The local name g_c becomes an alias for globals()["g_c"]
        g_c = 4
        print("In sound_practice, the name g_c points to: " + str(g_c))


t = TestClass()
t.direct_print()
t.mod_without_dec()
t.mod_with_late_dec()
t.mod_without_dec_error()
t.sound_practice()

#4


1  

class flag:
    ## Store pseudo-global variables here

    keys=False

    sword=True

    torch=False


## test the flag class

print('______________________')

print(flag.keys)
print(flag.sword)
print (flag.torch)


## now change the variables

flag.keys=True
flag.sword= not flag.sword
flag.torch=True

print('______________________')

print(flag.keys)
print(flag.sword)
print (flag.torch)

#5


0  

Its very simple to make variable as a global in side the class, we can use this global variable in any other functions inside the class as well

将变量作为类的全局变量非常简单,我们也可以在类中的任何其他函数中使用这个全局变量

a = 0

a = 0

class b(): global a a = 10

class b():global a a = 10

a 10

一个10