简体   繁体   中英

How do I use a static variable inside a class in Python

class Cls:
    counter = 0
    def __init__(self, name):
        self.name = name
        self.counter += 1
    def count(self):
        return self.counter

I'm learning python, what I want to have is a static counter that counts the number of times the class has been instantiated, but every time I create an instance counter gets recreated and count() function always returns 1. I want something that in java would look like this

public class Cls {
    private static int counter = 0;
    private String name;
    public Cls(String name) {
        this.name = name;
        counter ++;
    }
    public static int count(){
        return counter;
    }
}

There are two ways to access a class attribute: you can either access it directly on a class, or you can read it through self<\/code> (but not rebind it). Accessing a class attribute through self<\/code> won't work if there is already a value set directly on the instance so you would normally try to use the class to access a class attribute.

class Cls:
    counter = 0
    def __init__(self, name):
        self.name = name
        Cls.counter += 1
    def count(self):
        return Cls.counter

Do not use Cls.

class MyClass:
    counter = 0
    def __init__(self, name):
        self.name = name
        self.counter += 1  # this creates an instance variable counter 
                           # thats initialized by counter if you do not set it
                           # it is NOT shared between instances, but specific to each 

Instead you should increment the static variable:

    def __init__(self, name):
        self.name = name
        MyClass.counter += 1  # this increments the static class variable  

If you fix

    @staticmethod
    def count():
        return MyClass.counter

this way, you can still call count() on instances as well as directly on the class.

t = MyClass("some")
print( MyClass.count() )  # fine

t1 = MyClass("other")
print( t.count() )        # only allowed if prefix the method with @staticmethod

Output:

1
2

See What is the difference between @staticmethod and @classmethod in Python? for further infos.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM