0

I want to have a global variable x that can be accessed by multiple object instances: The module Obj should have something like:

x = 0

class Obj:  
  def set_x(self):    
      global x
      x = 2

  def print_x(self):    
      print x

...etc.

The other module (ex: main) instantiates the object obj:

obj1 = Obj.Obj()
obj1.set_x()
obj2 = Obj.Obj()
obj2.print_x

this should print 2

codeape
  • 97,830
  • 24
  • 159
  • 188
Academia
  • 3,984
  • 6
  • 32
  • 49

1 Answers1

2

I think you're looking for something like static variables (I'm not sure what they're called in Python). Have you tried something like:

class Obj:
   x = 0

   def set_x(self):
      Obj.x = Obj.x + 1

   def print_x(self):
      print Obj.x

Tests:

>>> obj1 = Obj()
>>> obj1.set_x()
>>> obj1.print_x()
1
>>> obj2 = Obj()
>>> obj2.set_x()
>>> obj2.print_x()
2
>>> obj1.print_x()
2

You should see this SO post for some more information.

Community
  • 1
  • 1
Dirk
  • 3,030
  • 1
  • 34
  • 40
  • What C calls "static variables" are called "global variables" in Python (even though they're not truly global). That is what the code sample in the question uses. The type of variable you're using here is called a "class attribute." – David Z Nov 28 '11 at 09:46
  • @dirk, thanks about user queryset issue comment in my answer (in other question). +1 – dani herrera Jan 29 '12 at 21:32