How to pass return value of method within class?

Viewed 398

What is the proper way to pass a returned value from a method within a class? Do you always call the method when needed or can the returned value be stored in the init method? Let's say I have:

class Foo():

    def __init__(self):

    def heavy_method(self):
        #slow crunching
        return crunch

    def use_heavy_crunch(self):
        data = self.heavy_crunch()
        for i in data:
            #do data stuff
            #return data stuff

    def other_func_that_need_heavy_method(self):
        pass

d = Foo()
d.use_heavy_crunch()

What I wonder is if above structure is the correct way or if the below way is equivalent or better?

class Foo()

    def __init__(self):
        self.data = None

    def heavy_method(self):
        #slow crunching
        self.data = crunch

    def use_heavy_crunch(self):
        for i in self.data:
            #do data stuff
            #return data stuff

    def other_func_that_need_heavy_method(self):
        pass

d = Foo()
d.heavy_method()
d.use_heavy_crunch()

So in the above example a method is called within an other method, while in the below example the return value of the method is passed to a variable in the init method and later on used in another function.

2 Answers

If I understand correctly you're trying to do something like

class Foo():

    def __init__(self):
        self.data = self.heavy_method() # we assign the return value to an attribute of our object

    def heavy_method(self):
        #slow crunching
        return crunch

    def use_heavy_crunch(self):
        for i in self.data: # Notice it's now self.data
            #do data stuff
            #return data stuff

    def other_func_that_need_heavy_method(self):
        pass

d = Foo()
d.use_heavy_crunch()

You don't want the initialization method of class to perform heavy processing tasks, its generally bad practice, the class initialization should only be used to initialize class based instance variable. If you are planning to call d.use_heavy_crunch() multiple times in future after the instance d is created and the return value of d.heavy_method() did not change over time then the second approach is good way to go, as in case of first approach every time you call d.use_heavy_crunch() you are calling d.heavy_method() and performing the same tasks repeatedly. In the second approach you would only call d.heavy_method() once and later use its result in other methods of class.

Related