Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I need a Python class that keep tracks of how many times it is instantiated

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.

like image 752
BlogueroConnor Avatar asked Nov 29 '22 06:11

BlogueroConnor


1 Answers

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.

like image 61
Paolo Bergantino Avatar answered Dec 05 '22 03:12

Paolo Bergantino