1

I was practicing writing a class and ended up with this problem. I wrote a class that should return the value of the function after 5th instance is generated and do nothing for instances less than 5. I wrote the below code, but the instance count is not added every time I create an instance. The display in __init__ shows 1 for the first instance and after that the display is not there.. I would like to know what is that I am missing. I just felt like __init__ is not called after the first instance call. I checked by removing the 'IF' condition in the __call__ and every time the result of the function 10 is displayed but count is not increasing.

class After5(object):
    call_count = 0
    def __init__(self, funct):

        After5.call_count += 1
        print('Count{0}'.format(After5.call_count))
        self.funct = funct
    def __call__(self):
        if After5.call_count > 5:  #enter code here
            res = self.funct()
            print('{0}'.format(res))
            print('Sending Results{0}'.format(After5.call_count))
        return res

@After5
def dummy_funct():
    return 5 * 2

dummy_funct()
dummy_funct()
dummy_funct()
dummy_funct()
dummy_funct()
dummy_funct()
quamrana
  • 37,849
  • 12
  • 53
  • 71
Bharath Bharath
  • 45
  • 1
  • 1
  • 10
  • [you're welcome](https://stackoverflow.com/questions/279561/what-is-the-python-equivalent-of-static-variables-inside-a-function) – IMCoins Dec 22 '17 at 20:00
  • 2
    The `After5` class generates an instance only when you use it as a decorator. Each of your six calls of the decorated function go through the `__call__` method of the instance you created. – quamrana Dec 22 '17 at 20:14
  • FYI, you can achieve your intended result using a wrapper function instead of a wrapper class: https://ideone.com/8kSWYa – Robᵩ Dec 22 '17 at 20:21
  • @ Quamrana - I am not getting/understanding your explanation. Can you please explain in detail? Thanks for all your help. – Bharath Bharath Dec 27 '17 at 20:08
  • I got it and thanks for the help. Instead of incrementing the counter in __init__ whenever an instance has to be created, I did in __call__ and it worked. – Bharath Bharath Jan 03 '18 at 19:04

0 Answers0