Return class object after changing object variables

Question:

Im new to OOP in Python (and in general) and wondering about the correct way to change object variables. Since Python cant return void i need to return something when an object variable has changed.

class classA:
   var_a = 1
   var_b = 1

def changeSomething(classAObj):
    classAObj.var_a = 2
    return classAobj

def main()
    classAObj = classA()
    changeSomething(classAObj)
    .....use object with new changes here....

Is it correct to return the entire classAObj in the changeSomething function? Or should i only return the variable i.e

...
return classAobj.var_a

I get the same result in either way, classAObj.var_a has changed in both cases, but what is the correct way to do it?

Asked By: user19699160

||

Answers:

changeSomething should not return anything; when it modifies the argument in place, it should return nothing (implicitly None). Only functions that make new modified copies should return them (and leave the argument unmodified).

So your code should just be:

class classA:
   def __init__(self):
       self.var_a = 1  # You forget self here
       self.var_b = 1  # You forget self here

def changeSomething(classAObj):
    classAObj.var_a = 2  # Fix name, self wouldn't exist, you received it by a different name

def main():
    classAObj = classA()
    changeSomething(classAObj)  # classAObj is modified in place, so changes seen in caller
    # .....use object with new changes here....

Or, given this is a class, it makes sense to have changeSomething be an instance method, e.g.:

class classA:
   def __init__(self):
       self.var_a = 1  # You forget self here
       self.var_b = 1  # You forget self here

    # Indented to make it a method of the class
    def changeSomething(self):  # Argument renamed to follow standard naming for instance methods
        self.var_a = 2

def main():
    classAObj = classA()
    classAObj.changeSomething()  # Use method call syntax, classAObj still modified in place
    # .....use object with new changes here....
Answered By: ShadowRanger
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.