What is equivalent to the Ruby class @@ variable in Python?

In Ruby 1.9, I can use its class variable as shown below:

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 higher in Python 2.5+?

+3
source share
1 answer
class Sample(object):
  _count = 0

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

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

Usage is slightly different from Ruby; for example, if you have this code in a module a.py,

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

having a class property Sample.count (with the same name as the instance property) will be a bit complicated in Python (perhaps, but don't bother IMHO).

+6
source

Source: https://habr.com/ru/post/1741491/


All Articles