0

In Python, you could define a function attribute "call_count" such that:

def counter(func):
    def inner(*args):
        inner.call_count+= 1
        return func(*args)

    inner.call_count= 0
    return inner

def sum(a, b, c):
    return a+b+c

sumCounter= counter(sum)

print(sumCounter(1,2,3))
print(sumCounter.call_count)

print(sumCounter(3,2,2))
print(sumCounter.call_count)

This prints:

6
1
7
2

What if, instead of being able to call sumCounter.call_count, I'd want to call a function attribute sumCounter.call_count()? That is, a function attribute that "looks" like a class method? How could this be done?

  • You could store a function in `inner.call_count` just as easily as you stored an integer - why do you think this would be a problem? I'm not sure what the point is in this case, as you're still going to need to store an integer *somewhere*, to maintain the count. – jasonharper Nov 01 '20 at 04:16

2 Answers2

0

You can either have a variable named call_count or a function named call_count, but not both. And in either case, you do need some variable.

def counter(func):
    def inner(*args):
        inner._call_count+= 1
        return func(*args)

    inner._call_count= 0
    inner.call_count = lambda: _call_count
    return inner
Frank Yellin
  • 9,127
  • 1
  • 12
  • 22
0

Functions are first class objects. They work just like instances of any class (because they are an instance of a class). You can assign any attributes to them, including other functions.

def counter(func):
    def inner(*args):
        inner._call_count+= 1
        return func(*args)
    
    inner._call_count= 0
    def call_count():
        return inner._call_count
    inner.call_count = call_count
    return inner

sytech
  • 29,298
  • 3
  • 45
  • 86