繁体   English   中英

Python:像Java一样的静态类变量?

[英]Python: static class variables like in Java?

在Java中,我可以给一个类一个静态变量,这里是它的计数器。 我在构造函数中递增它,这使得它的目的是跟踪从这个类中实例化了多少个对象

class Thing
{
    private static int counter;

    public Thing()
    {
        counter++;
    }

    public static int getCounter()
    {
        return counter;
    }

}

然后我可以通过使用(在主内部或任何地方)使用计数器

int counter = Thing.getCounter()

有没有办法在Python中这样做? 我知道你本质上可以有静态类变量/属性,不给它们一个下划线前缀,然后通过Class.attribute(而不是Object.attribute或Object.get_attribute)访问它们,但有没有办法在其中使用静态变量类本身,就像我在Java示例中所做的那样,我在构造函数中使用了静态类变量? 有一个像'self'这样的关键字是有道理的,尽管如果有的话我还没弄明白

class Thing:
    counter = 0

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

    def getCounter():
        return Thing.counter

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

暂无
暂无

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

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