繁体   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

我正在学习 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;
    }
}

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

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

不要使用 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 

相反,您应该增加静态变量:

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

如果你修复

    @staticmethod
    def count():
        return MyClass.counter

这样,您仍然可以在实例上以及直接在类上调用 count()。

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

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

输出:

1
2

请参阅Python 中的 @staticmethod 和 @classmethod 有什么区别? 了解更多信息。

暂无
暂无

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

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