I am not a complete beginner but fairly new to Python. Whilst working on a project today I just had an idea and wondered regarding the usage of \"self>
If you dont use self.some_temp_var
, then you are defining a local variable which will be garbage collected after the constructor.
So yes you need self
if you want to define an instance attribute that should persist with the instance. Whether you need it to be public or private is a matter of naming. Prefix it with an _
for protected or __
for private.
If some_temp_var
is just a temp for the constructor and you never need it again then no, you dont need self
. It is about persistence and member attributes. You do not need self
for the pure fact of working with a variable within a single method.
Consider this... What if some_temp_var
were some huge data structure that you build up to arrive at the real result value? You dont want to use self
to store a temp variable because it wont free memory until you delete it or the instance. You want it to be cleaned up when it is no longer needed.