什么';s相当于Ruby';Python中的s类@变量?
在Ruby 1.9中,我可以使用其类变量,如下所示:什么';s相当于Ruby';Python中的s类@变量?,python,ruby,class-variables,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 如何在Pytho
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+中实现上述功能
class Sample(object):
_count = 0
def __init__(self):
Sample._count += 1
@property
def count(self):
return Sample._count
使用与Ruby有点不同;e、 g.如果模块a.py
中有此代码
>>> import a
>>> x = a.Sample()
>>> print x.count
1
>>> y = a.Sample()
>>> print x.count
2
拥有Sample.count“class property”(与实例属性同名)在Python中可能有点棘手(可行,但不值得麻烦)。如果希望与类变量或singleton类(
class)的实例变量具有相同的行为,则可能需要精确