Search code examples
pythonrubyclass-variables

What's the equivalent of Ruby's class @@variable in Python?


In Ruby 1.9, I can use its class variable like the following:

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

How can I achieve the above in Python 2.5+ ?


Solution

  • class Sample(object):
      _count = 0
    
      def __init__(self):
        Sample._count += 1
    
      @property
      def count(self):
        return Sample._count
    

    The use is a bit different from Ruby; e.g. if you have this code in module a.py,

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

    having a Sample.count "class property" (with the same name as the instance property) would be a bit tricky in Python (feasible, but not worth the bother IMHO).