我需要一个 Python 类来跟踪它被实例化的次数
我需要一个像这样工作的类:
>>> a=Foo()
>>> b=Foo()
>>> c=Foo()
>>> c.i
3
这是我的尝试:
class Foo(object):
i = 0
def __init__(self):
Foo.i += 1
它按要求工作,但我想知道是否有更Pythonic的方法来做到这一点。
I need a class that works like this:
>>> a=Foo()
>>> b=Foo()
>>> c=Foo()
>>> c.i
3
Here is my try:
class Foo(object):
i = 0
def __init__(self):
Foo.i += 1
It works as required, but I wonder if there is a more pythonic way to do it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您想担心线程安全(以便可以从实例化 Foo 的多个线程修改类变量),那么上面的答案是正确的。 我在此处提出了有关线程安全的问题。 总之,您必须执行以下操作:
现在 Foo 可以从多个线程实例化。
If you want to worry about thread safety (so that the class variable can be modified from multiple threads that are instantiating
Foo
s), the above answer is in correct. I asked this question about thread safety here. In summary, you would have to do something like this:Now
Foo
may be instantiated from multiple threads.滥用装饰器和元类。
通过频繁使用双下划线名称,您可以看出它是 Pythonic 的。 (开玩笑,开玩笑……)
Abuse of decorators and metaclasses.
You can tell it's Pythonic by the frequent use of double underscored names. (Kidding, kidding...)
没有。 那很好。
来自《Python 之禅》:“简单胜于复杂。”
这很好用,而且很清楚你在做什么,不要让它复杂化。 也许将其命名为
counter
或其他名称,但除此之外,您可以尽可能地使用 pythonic。Nope. That's pretty good.
From The Zen of Python: "Simple is better than complex."
That works fine and is clear on what you're doing, don't complicate it. Maybe name it
counter
or something, but other than that you're good to go as far as pythonic goes.