henry
henry

Reputation: 965

Count How Many Times a Function is Excuted after the Exceution of Another Function for an Instance of a Class

Based on this question, I know how to count how many times a function FUNCTION was executed within an instance of a class CLASS. Now, I have another question: How would I count how many times (for one instance of the class CLASS) a second function FUNCTION2 is executed after the first function FUNCTION is executed ?

Here is a small example of how I tried it:

class CLASS:
    # Initializing counting for first function
    counting_function_execution  = 0

    def __init__(self,name):
        self.name = name

    def FUNCTION1(self):
        # Initializing counting for second function
        counting_excution_after_FUNCTION = 0

        self.counting_function_execution += 1
        print("FUNCTION 1 was excecuted ", self.counting_function_execution, " time.")

    def FUNCTION2(self):
        counting_excution_after_FUNCTION += 1
        print("FUNCTION 2 was excecuted ", self.counting_excution_after_FUNCTION, " time after FUNCTION.")

...but I got:

test = CLASS("Fred")
test.FUNCTION1()
test.FUNCTION2()
test.FUNCTION2()

the output:

FUNCTION 1 was excecuted  1  time.
---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
<ipython-input-148-d67aeefa671e> in <module>()
      1 test = CLASS("Fred")
      2 test.FUNCTION1()
----> 3 test.FUNCTION2()
      4 test.FUNCTION2()

<ipython-input-147-6a6d7adb1af9> in FUNCTION2(self)
     15 
     16     def FUNCTION2(self):
---> 17         counting_excution_after_FUNCTION += 1
     18         print("FUNCTION 2 was excecuted ", self.counting_excution_after_FUNCTION, " time after FUNCTION.")

UnboundLocalError: local variable 'counting_excution_after_FUNCTION' referenced before assignment

Upvotes: 1

Views: 38

Answers (1)

Mark
Mark

Reputation: 92440

If you keep track of how many times FUNCTION1 is called, you can test for that in FUNCTION2 and make sure it's above zero before you start counting FUNCTION2:

class CLASS:

    def __init__(self,name):
        self.name = name
        # initialize instance counters -- each instance gets its own counts
        self.counting_function_execution_1 = 0
        self.counting_function_execution_2 = 0

    def FUNCTION1(self):
        self.counting_function_execution_1 += 1
        print("FUNCTION 1 was excecuted ", self.counting_function_execution_1, " number of times.")

    def FUNCTION2(self):
        if self.counting_function_execution_1:     # don't count unless function1 has run
            self.counting_function_execution_2 += 1
        print("FUNCTION 2 was excecuted ", self.counting_function_execution_2, " number of times after FUNCTION.")

c = CLASS('the dude')
c.FUNCTION2() #0
c.FUNCTION2() #0
c.FUNCTION1()

c.FUNCTION2() #1
c.FUNCTION2() #2

Upvotes: 1

Related Questions