gpt4 book ai didi

python - Python 中 Ruby 类 @@variable 的等价物是什么?

转载 作者:数据小太阳 更新时间:2023-10-29 07:29:33 25 4
gpt4 key购买 nike

在 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“类属性”(与 instance 属性同名)在 Python 中会有点棘手(可行,但不值得麻烦恕我直言)。

关于python - Python 中 Ruby 类 @@variable 的等价物是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2655104/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com