Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to calcutate several functions in class without reiteration

I need to calculate some variables, which can be used by other variables:

class Variables:
    def __init__(self, param1, param2):
        self._param1 = param1
        self._param2 = param2
    
    def var1(self):
        return self._param1 + 'foo'
    def var2(self):
        return var1() + 'bar'
    ....
    def var9(self):
        return var2() + var8()
    def var10(self):
        return var3() + var9()

Problem is that intermediate functions var1..var9 are calculating multiple times when I call them outside module. I tried to calculate them in __init__:

def var1(self):
    return self._param1 + 'foo'
def var2(self):
    return self._var1 + 'bar'
....
def var9(self):
    return self._var2 + self._var8
def var10(self):
    return self._var3 + self._var9


    class Variables:
        def __init__(self, param1, param2):
            self._param1 = param1
            self._param2 = param2
            
            self._var1 = var1(self)
            self._var2 = var2(self)
            ....
            self._var9 = var9(self)
            self._var10 = var10(self)

But my intuition tells me that this decision is terrible: self-s inside and outside class are "different".
For some reasons I need 10 separate functions and cant combine them in one big function. What is the best way to calculate and store them?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

class Variables:
    def __init__(self, param1, param2):
        self._param1 = param1
        self._param2 = param2

        self._var1 = self._generate_var1()
        ... similarly for var2 through var10

    def _generate_var1(self):
        var1 = self._param1 + 'foo'
        return var1

    def var1(self):
        return self._var1

    ... similarly for var2 through var10
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading