Question

I'm writing a game in Python with the Pygame2 multimedia library, but I'm more accustomed to developing games with ActionScript 3. In AS3, I don't think it was possible to store an object in a static variable, because static variables were initialized before objects could be instantiated.

However, in Python, I'm not sure if this holds true. Can I store an object instance in a Python class variable? When will it be instantiated? Will one be instantiated per class or per instance?

class Test:
    counter = Counter() # A class variable counts its instantiations
    def __init__(self):
        counter.count() # A method that prints the number of instances of Counter

test1 = Test() # Prints 1
test2 = Test() # Prints 1? 2?
Was it helpful?

Solution

Yes.
As with most python try it and see.

It will be instantiated when a Test object is created. ie your assignment to test1
The counter object is created per class

Run the following to see (to access the class variable you need the self

class Counter:
  def __init__(self):
    self.c = 0

  def count(self):
    self.c += 1
    print 'in count() value is ' , self.c
    return self.c

class Test:
  counter = Counter() # A class variable counts its instantiations 
  print 'in class Test'
  def __init__(self):
    print 'in Testinit'
    self.counter.count() # A method that prints the number of instances of Counter

test1 = Test() # Prints 1
test2 = Test()

OTHER TIPS

You can do this:

class Test:
  counter = 0
  def __init__(self):
    Test.counter += 1
    print Test.counter

And it works as expected.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top