Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python3 - When exactly do you need to prepend "self._" to variable declarations within class methods? [duplicate]

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!

like image 814
user2351418 Avatar asked May 18 '15 02:05

user2351418


1 Answers

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.

like image 179
jcoppens Avatar answered Nov 15 '22 10:11

jcoppens