我需要一个Python类来跟踪它被实例化的次数

问题描述:

我需要一个这样的类:

>>> a=Foo()
>>> b=Foo()
>>> c=Foo()
>>> c.i
3

这里是我的尝试:

class Foo(object):
    i = 0
    def __init__(self):
        Foo.i += 1

它可以按需工作,但我想知道是否有更多的pythonic方法。

It works as required, but I wonder if there is a more pythonic way to do it.

不。这很不错。

来自Python的禅:简单比复杂更好。

From The Zen of Python: "Simple is better than complex."

罚款,清楚你在做什么,不要使它复杂化。也许把它命名为 counter 或者什么,但除此之外,你还是可以走到pythonic去。

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.