4

In Java, I can give a class a static variable, here it's counter. I'm incrementing it in the constructor, which gives it the purpose of keeping track of how many objects have been instantiated from this class

class Thing
{
    private static int counter;

    public Thing()
    {
        counter++;
    }

    public static int getCounter()
    {
        return counter;
    }

}

I could then use counter by using (inside of main, or wherever)

int counter = Thing.getCounter()

Is there any way of doing this in Python? I know you can essentially have static class variables/attributes by not giving them an underscore prefix, and then accessing them through Class.attribute (rather than Object.attribute or Object.get_attribute), but is there any way to use a static variable within the class itself, just like I did with the Java example where I used a static class variable inside the constructor? It would make sense for there to be a keyword like 'self' for this, although if there is I've not figured it out

  • 1
    You can access a class variable with `Class.attribute` from inside a method of the class just like you can from outside the class. – BrenBarn Jun 15 '16 at 22:32
  • This SO post from the past likely answers your question too: http://stackoverflow.com/questions/68645/static-class-variables-in-python – Barry Jun 15 '16 at 22:34

1 Answers1

3
class Thing:
    counter = 0

    def __init__(self):
        Thing.counter += 1

    @staticmethod
    def getCounter():
        return Thing.counter

Example

>>> a = Thing()
>>> b = Thing()
>>> Thing.getCounter()
2
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • Thanks, this all works (I was going to say that you still have to use self in the method arguments, but I tried it without and it works fine, even though it gives me a red underline) I did try this earlier with Thing as the prefix, but I guess it didn't work because I was also changing the self in the method arguments to Thing as well. –  Jun 15 '16 at 22:41
  • 3
    `getCounter` is not an instance method, but a class method, hence you don't need (and want) `self` to be the first argument. Be careful, that contrary to most other OO languages `a` and `b` will have their own `counter` variable, so `a.counter` is different from `Thing.counter`! – Jan Christoph Terasa Jun 16 '16 at 12:36