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

时间:2018-04-09 15:40:17

标签: python python-3.x

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;
    }
}

2 个答案:

答案 0 :(得分:6)

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

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

当您编写self.counter += 1时,这是self.counter = self.counter + 1的简写,与通过self的任何其他绑定一样,它会设置实例属性。

如果您想要实例属性的默认值,这可能很有用,您可以将它们设置为类属性,然后只需要在需要不同值的实例中更新它们,但为了避免混淆,您可能希望避免使用{{1在访问类属性时完全没有。

您还可以考虑将self方法转换为类方法并将增量移动到另一个方法中:

count

如果你这样做,那么每个子类都有自己独立的计数器。这可能是也可能不是你想要的。这里的@classmethod def increment(cls): cls.counter += 1 @classmethod def count(cls): return cls.counter 参数是实际实例化的类,如果你可以使用整个类层次结构,或者甚至只是一个基类cls,你可以将这段代码放在一起并重复使用它多个独立柜台。

CountsInstances装饰每个函数将为您提供接近Java代码的东西:

@staticmethod

答案 1 :(得分:0)

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

有关更多信息,请参阅What is the difference between @staticmethod and @classmethod in Python?