简体   繁体   中英

Python - modify a global variable

I'm using python for create an application. 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?

Your global declaration is at the wrong place; it needs to be at the point you assign to the variable, ie inside 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.

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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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