Sorry, this is a really basic question, but I am just wondering when it is necessary to prepend self._
to variable declarations within methods? Every time I declare a variable within a method should I declare it with self._
included? Is there any situation where I should not do this?
Which of these methods would be valid for example (for some hypothetical class):
def thing_counter(self, thing):
length_of_thing = len(thing)
return length_of_thing
OR
def thing_counter(self, thing):
self._length_of_thing = len(thing)
return self._length_of_thing
Both work, but which would be strictly correct?
I know that a variable declaration is not really needed here, I am just trying to use a simple example.
Cheers!
Both work equally.
In the first version, length_of_thing
will be created inside the function, and the return
will return a copy to the caller. length_of_thing
itself will not exist anymore after the return.
In the second one, self._length_of_thing
will be created, not inside the function, but inside the instance of the class. The result is that it will be visible to all other methods. And the return
still returns a copy.
So possibly this version uses a little more memory, as the variable self._length_of_thing
remains alive till the instance of the class is destroyed.
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