Search code examples
pythonfunctionclassmethodsself

Is self variable computed multiple times if functions are called more than once in Python?


I have a class where the shared variable self.a is obtained after a very heavy computation which requires a lot of time:

class MyClass(object):
def __init__(self):
    # ----------------------------------
    # function computationally demanding 
    out = demanding_function() # In this example, the output is a list of characters ['A','X','R','N','L']
    # ----------------------------------
    self.a = out  

def fun1(self, string):
    out = []
    for letter in self.a:
        out.append(string+letter)
    return out

def fun2(self, number):
    out = []
    for letter in self.a:
        out.append(str(number)+letter)
    return out

o = MyClass()
x = o.fun1('Hello ')
y = o.fun2(2)

As you can see, self.a is used by the functions fun1 and fun2. Here is my question is the following: if I call those 2 functions, is the demanding_function() executed multiple times or just once?

Note: this is a generic example and the variables don't have any specific meaning


Solution

  • The function is called just once, when the class instance is initialised i.e. when the __init__ of the class is called. Every other time you access self.a, the already assigned value is used; so no worries.