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 inst_2(self): self.var = self.inst_mtd() # or in init if desired
Option 2:
def inst_mtd(self): self.var = True
Option 3:
def inst_mtd(self): self.var = True return self.var def inst_2_or_init(self): self.var = self.inst_mtd()
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 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
.
Thanks!