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

4
  • 1
    OK... so what is your question? Also, why wouldn't you just use a class attribute for that? Commented Nov 28, 2011 at 7:31
  • Instance methods take self as the first argument. I have edited the code in the question. Commented Nov 28, 2011 at 7:41
  • Whats ur question? When you tried wht did you get as output? Commented Nov 28, 2011 at 7:55
  • I just copied and pasted your code into an Idle session, and it works as-is. Commented Nov 28, 2011 at 8:10

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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."
@dirk, thanks about user queryset issue comment in my answer (in other question). +1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.