Search code examples
pythonclasscounterinstance-variables

How to create instance specific function counter?


I would like to track function count inside the class but such that this count is different for each instance of the class.

We can set up a counter on a simple function:

def foo1():
    pass

foo1.count = 0
foo1.count +=1
print(foo1.count)

Now let`s turn to class methods:

class A:
    def foo2(self):
        print('Hi')

we can set counter here as well

A.foo2.count = 0
a = A()
b = A()

but this count is NOT instance specific

A.foo2.count += 1
print(a.foo2.count)
print(b.foo2.count)

it is not possible to set count for an INSTANCE method:

a.foo2.count += 1

and if we use __func__ it will be equivalent to changing A.foo2.count:

a.foo2.__func__.count += 1
print(b.foo2.count)
print(a.foo2.count)
print(A.foo2.count)

Question: how to make foo2.count INSTANCE specific ? So that a and b could have multiple values of foo2.count ?

Please note: I am asking about function attribute, not class attribute.


Solution

  • Maybe this then?

    from collections import defaultdict
    
    
    def foo1():
        print('Hi')
    foo1.count = defaultdict(int)
    
    class A:
    
        def foo2(self):
            foo1()
            foo1.count[self] += 1
    
    
    
    a = A()
    b = A()
    
    a.foo2()
    a.foo2()
    b.foo2()
    
    print(foo1.count)
    

    output:

    Hi
    Hi
    Hi
    defaultdict(<class 'int'>, {<__main__.A object at 0x000001E59759ABE0>: 2, <__main__.A object at 0x000001E596AFCD30>: 1})