Question

How should I pass a variable in between methods in a class? Like this, as an argument:

class Yadayada:
    def foo(self):
        for i in somelist:
            pass_var = i * blah blah blah
            output = self.bar(pass_var)

    def bar(self,pass_var):
        a= pass_var * whatever
        return a

or like this, store it in a variable?

class Yadayada:
    def foo(self):
        for i in somelist:
            self.pass_var = i * blah blah blah
            output = self.bar()

    def bar(self):
        a= self.pass_var * whatever
        return a

What's the best way and why? Or does it even matter? Note: I will not be using the variable pass_var in the rest of the code.

Was it helpful?

Solution

This is a design decision. Passing it as a parameter will keep that passed value around for the life of that function. Storing it as an attribute on the object will keep it around for the life of the instance - that is likely to be much longer.

The question you should ask yourself is does this value help describe the instance or is it something the instance owns? - if either of these things are true, then store it.

If it's just something used to compute a value (which is what it sounds like) then there is no reason to store it. Storing it implies you want to use it later.

If you are unsure, err on the side of passing the value to the function. This reduces the chance for error (calling the function when the value isn't set on the class), and it reduces the amount of memory being used.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top