user6158787
user6158787

Reputation:

Python: static class variables like in Java?

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

Upvotes: 4

Views: 1229

Answers (1)

Cory Kramer
Cory Kramer

Reputation: 117866

class Thing:
    counter = 0

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

    @staticmethod
    def getCounter():
        return Thing.counter

Example

>>> a = Thing()
>>> b = Thing()
>>> Thing.getCounter()
2

Upvotes: 3

Related Questions