【问题标题】:Python: static class variables like in Java?Python:像Java中的静态类变量?
【发布时间】:2016-06-15 22:24:12
【问题描述】:

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

class Thing
{
    private static int counter;

    public Thing()
    {
        counter++;
    }

    public static int getCounter()
    {
        return counter;
    }

}

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

int counter = Thing.getCounter()

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

【问题讨论】:

  • 您可以从类的方法内部使用Class.attribute 访问类变量,就像从类外部访问一样。
  • 过去的这篇 SO 帖子也可能回答了您的问题:stackoverflow.com/questions/68645/…

标签: java python class oop


【解决方案1】:
class Thing:
    counter = 0

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

    @staticmethod
    def getCounter():
        return Thing.counter

例子

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

【讨论】:

  • 谢谢,这一切都有效(我要说你仍然必须在方法参数中使用 self,但我没有尝试过它,它工作正常,即使它给了我一个红色下划线)我之前确实尝试过以 Thing 作为前缀,但我猜它不起作用,因为我还将方法参数中的 self 也更改为 Thing。
  • getCounter 不是实例方法,而是类方法,因此您不需要(也不希望)self 成为第一个参数。请注意,与大多数其他 OO 语言相反,ab 将有自己的 counter 变量,因此 a.counterThing.counter 不同!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-05
  • 2015-10-23
  • 1970-01-01
  • 1970-01-01
  • 2013-09-08
  • 1970-01-01
相关资源
最近更新 更多