I'm curious about the recommended way to return a value for instance methods in Python. I'm sorry if this comes across as a rather trivial question, but I can't seem to find a proper answer on google/sx/so.
Option 1:
class Cla:
def __init__(self):
self.var = False
def _inst_mtd(self):
var = True
return var
def calc_var(self):
self.var = self._inst_mtd() # or in init if desired
def return_var(self):
return self.var
Option 2:
class Cla:
def __init__(self):
self.var = False
def _inst_mtd(self):
self.var = True
def calc_var(self):
self._inst_mtd()
def return_var(self):
return self.var
Option 3:
class Cla:
def __init__(self):
self.var = False
def _inst_mtd(self):
self.var = True
return self.var
def calc_var(self):
self.var = self._inst_mtd()
def return_var(self):
return self.var
The intention of _inst_mtd
is to calculate a value for self.var
. A separate public method to return self.var
will provide the return
function to an outside caller . _inst_mtd
is meant to be called within the class, perhaps in a loop, and perhaps with a public method calc_var
if for instance it'll take a while to run .
My concerns are that 1 might result in confusion between local and instance variables, if the whole point of _inst_mtd
is to modify self.var
and not actually deal with another variable called var
. For 2, I'm under the impression that (considering only _inst_mtd
) this constitutes a side-effect, which should be avoided? But 3 just seems unnecessary, although it does work well with return type annotations, especially when the type (not recommended) or elements within are changed in _inst_mtd
.