Python中Ruby的类@@变量的等价物是什么?

时间:2010-04-16 17:51:27

标签: python ruby class-variables

在Ruby 1.9中,我可以使用它的类变量,如下所示:

class Sample
  @@count = 0

  def initialize
    @@count += 1
  end

  def count
    @@count
  end
end

sample = Sample.new
puts sample.count     # Output: 1

sample2 = Sample.new
puts sample2.count    # Output: 2

如何在Python 2.5+中实现上述目标?

1 个答案:

答案 0 :(得分:6)

class Sample(object):
  _count = 0

  def __init__(self):
    Sample._count += 1

  @property
  def count(self):
    return Sample._count

使用与Ruby略有不同;例如如果您在模块a.py中有此代码,

>>> import a
>>> x = a.Sample()
>>> print x.count
1
>>> y = a.Sample()
>>> print x.count
2

拥有一个Sample.count“类属性”(与实例属性同名)在Python中会有点棘手(可行,但不值得麻烦恕我直言)。