jeudi 9 février 2017

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

Vote count: 0

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

asked 16 secs ago

Let's block ads! (Why?)



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

Aucun commentaire:

Enregistrer un commentaire