Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python store in self variable vs. passing to def

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.

like image 398
jason Avatar asked May 09 '14 18:05

jason


People also ask

What is the purpose of self variable in Python?

The self variable is used to represent the instance of the class which is often used in object-oriented programming. It works as a reference to the object. Python uses the self parameter to refer to instance attributes and methods of the class.

Do you need to pass in self Python?

Python3. Self is the first argument to be passed in Constructor and Instance Method. Self must be provided as a First parameter to the Instance method and constructor. If you don't provide it, it will cause an error.

Why do we pass in self as an argument in Python?

The self is used to represent the instance of the class. With this keyword, you can access the attributes and methods of the class in python. It binds the attributes with the given arguments. The reason why we use self is that Python does not use the '@' syntax to refer to instance attributes.

Can we replace self in Python?

self is only a reference to the current instance within the method. You can't change your instance by setting self .


1 Answers

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.

like image 78
Gareth Latty Avatar answered Oct 22 '22 08:10

Gareth Latty