Python中相当于Ruby类的@@变量是什么?
在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 个回答
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
那么在Python中,想要有一个叫做Sample.count的“类属性”(和实例属性同名)会有点麻烦(虽然可以做到,但我觉得没必要费这个劲)。