Python 中 Ruby 的 @@variable 类相当于什么?
在 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
How can I meet the above in Python 2.5+ ?
In Ruby 1.9, I can use its class variable like the following:
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 the above in Python 2.5+ ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
用法与Ruby有些不同;例如,如果您在模块
a.py
中有此代码,那么拥有 Sample.count “类属性”(与 instance 属性同名)会有点棘手在Python中(可行,但不值得麻烦恕我直言)。
The use is a bit different from Ruby; e.g. if you have this code in module
a.py
,having a Sample.count "class property" (with the same name as the instance property) would be a bit tricky in Python (feasible, but not worth the bother IMHO).