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中实现上述功能?
解决方法:
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中会有点棘手(可行,但不值得麻烦恕我直言).
标签:python,ruby,class-variables 来源: https://codeday.me/bug/20190827/1740996.html