简体   繁体   English

Python-修改全局变量

[英]Python - modify a global variable

I'm using python for create an application. 我正在使用python创建应用程序。 I have two different classes and I'm playing with a global variable. 我有两个不同的类,并且正在使用全局变量。 What I want to do is something like this 我想做的是这样的

globvar = 0

class one:
  global globvar
  def __init__()
    ...
  def func1()
    ...
    globvar = 1

class two:
  global globvar
  def __init__()
    ...
  def func2()
    ...
    print globvar  # I want to print 1 if I use func1

I've done something similar but func2 never print 1, but only 0. So the question is... it's possible change a global variable through different classes? 我做过类似的事情,但func2从不打印1,而只打印0。所以问题是...可以通过不同的类更改全局变量吗?

Your global declaration is at the wrong place; 您的全局声明在错误的位置; it needs to be at the point you assign to the variable, ie inside func1 . 它必须在您分配给变量的位置,即在func1内部。

That said, there is a much better way of addressing this, without using global at all: make globvar a class attribute on a base class that one and two both inherit from. 也就是说,有一个更好的方法可以解决此问题,而根本不使用global:将globvar基类的一个类属性,一个和两个都继承自该基类。

class Base(object):
    globvar = 0

class One(Base):
    def func1(self):
        self.__class__.globvar = 1

class Two(Base):
    def func2(self):
        print self.globvar

(Note in func1 you need to assign via self.__class , but in func2 you can access it directly on self , as Python will fall back to the class scope if it doesn't find it on the instance.) (请注意,在func1您需要通过self.__class进行分配,但在func2您可以直接在self上进行访问,因为如果Python在实例上找不到它,则会退回到类作用域。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM