El_Merendero
El_Merendero

Reputation: 699

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?

Upvotes: 0

Views: 267

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599956

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

Upvotes: 3

Related Questions