简体   繁体   English

"如何在 Python 的类中使用静态变量"

[英]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我正在学习 python,我想要的是一个静态计数器,它计算类被实例化的次数,但是每次我创建一个实例counter时都会重新创建并且count()函数总是返回 1。我想要一些在java中看起来像这样

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).有两种访问类属性的方法:您可以直接在类上访问它,也可以通过self<\/code>读取它(但不能重新绑定它)。 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.如果已经直接在实例上设置了值,则通过self<\/code>访问类属性将不起作用,因此您通常会尝试使用该类来访问类属性。

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

Do not use Cls.不要使用 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.这样,您仍然可以在实例上以及直接在类上调用 count()。

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?请参阅Python 中的 @staticmethod 和 @classmethod 有什么区别? for further infos.了解更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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