There is simple class:
class A(object): __COUNTER = 0 def do_something_1(self): ... def do_something_2(self): ...
Here's the simple version: How to increment a class-wide counter every time a particular function is called. The function can be __init__
, which covers your specific question.
class cls(object):
counter = 0
def __init__(self):
self.__class__.counter += 1
print self.__class__.counter
a = cls() # Prints 1
b = cls() # Prints 2
As you can see, the trick is to increment self.__class__.counter
, not self.counter
. You can do that inside any member function.
But don't use names starting with a double underscore, because they have special meaning for python (unless you know and want the special meaning, of course). If you want to flag the counter as private, use a single underscore: _counter
.