henry
henry

Reputation: 975

Counting Number of Times a Function of a Class is Excuted

I would like to count how many times I execute a specific function FUNCTION in a class CLASS. I tried to do it by definig a global variable within the class counting_function_execution and increasing it every time the function is executed:

class CLASS:
    global counting_function_execution 
    counting_function_execution  = 0

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

    def FUNCTION(self):
        print("Hi " + self.name)
        print("This function was already excecuted ", counting_function_execution, " number of times.")
        counting_function_execution += 1

However, when I do it:

test = CLASS("Fred")
test.FUNCTION()
test.FUNCTION()

I get:

---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
<ipython-input-104-dc8f3ae96700> in <module>()
      1 test = CLASS("Fred")
----> 2 test.say_hi()

<ipython-input-100-d0166079c633> in say_hi(self)
      8     def say_hi(self):
      9         print("Hi " + self.name)
---> 10         print("This function was already excecuted ", counting_function_execution, " number of times.")
     11         counting_function_execution += 1
     12 

UnboundLocalError: local variable 'counting_function_execution' referenced before assignment

Upvotes: 0

Views: 780

Answers (4)

figlio perduto
figlio perduto

Reputation: 170

If you are counting the execution per class, you can define something outside the class:

counting_function_execution = 0

def count_func(func):
    def decorator_count(self, *args, **kwargs):
        global counting_function_execution
        counting_function_execution += 1
        print(counting_function_execution)
        return func(self, *args, **kwargs)
    return decorator_count


class CLASS:
    # global counting_function_execution 
    # counting_function_execution  = 0

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

    @count_func
    def FUNCTION(self):
        print("Hi " + self.name)
        #print("This function was already excecuted ", self.counting_function_execution, " number of times.")

If you are counting the execution per instance, you just need to add self when referring to it, i.e. self.counting_function_execution.

class CLASS:
    # global counting_function_execution 
    counting_function_execution  = 0

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

    def FUNCTION(self):
        print("Hi " + self.name)
        print("This function was already excecuted ", self.counting_function_execution, " number of times.")
        self.counting_function_execution += 1

Upvotes: 0

Mark
Mark

Reputation: 92481

Henry, you're getting some confusing answers here because it's not 100% clear what you want especially if you have multiple instances of the class. If you want ONE count for all variables, you need to reference the class variable from the instance like:

class CLASS:
    # static class counting_function_execution 
    counting_function_execution  = 0

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

    def FUNCTION(self):
        print("Hi " + self.name)
        print("This function was already excecuted ", self.counting_function_execution, " number of times.")
        self.__class__.counting_function_execution += 1

c = CLASS("mark")
c.FUNCTION()      # 0
c.FUNCTION()      # 1

d = CLASS("john")
d.FUNCTION()      # 2
d.FUNCTION()      # 3

print(CLASS.counting_function_execution) #4

This will print 0 - 3 and at the end CLASS.counting_function_execution will equal 4.

If you instead use self.counting_function_execution += 1 each instance will get its own count and CLASS.counting_function_execution will be zero at the end because you never actually increment it.

Either way you can avoid the global variable which is a bonus.

Upvotes: 1

Elro444
Elro444

Reputation: 136

The problem is, that in the function CLASS.FUNCTION, you are not referencing the class variable counting_function_execution, but rather, another local variable with the same name.
That is why the error is 'referenced before assignment', because you reference that local variable before you initialize it.

To reference the right variable, you can either use self.counting_function_execution (the instance's variable), or CLASS.counting_function_execution (the class's static variable)

Upvotes: 3

Alec
Alec

Reputation: 9575

counting_function_execution is a class variable. If you want to access it from an instance of the class, use self.counting_function_execution. If you'd like to access it from the class itself, use x.counting_function_execution, where x is the name of the class (CLASS in this case)

Both ways work for your example

Upvotes: 1

Related Questions