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.
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.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.Abuse of decorators and metaclasses.
You can tell it's Pythonic by the frequent use of double underscored names. (Kidding, kidding...)