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.
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.
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.
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.
self is only a reference to the current instance within the method. You can't change your instance by setting self .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With