Search code examples
pythonmutable

Updating internal python class parameters with external functions


I have an external function my_update_function which is not part of my class my_class (currently for design reasons). Now, I would like to update the internal parameters of my_class i.e. self.x and self.y using the external function my_update_function.

Please see this MWE, which describes my questions:

def my_update_function(arg1,args2):
    """
    Updates arg1 and arg2.
    """
    return arg1*arg1,arg2*arg2

class my_class(object):
    def __init__(self):
        self.x = 2
        self.y = 3
    def simulate(self):
        my_update_function(self.x,self.y)

However, I am wondering if there is some way (either by class re-design or otherwise) that I can update self.x and self.y without having to save the output of the function my_update_function as parameter values (and without having to include my_update_function as part of my class my_class) i.e I would rather not write this:

def simulate(self):
    self.x, self.y = my_update_function(self.x,self.y)

but would want it to be like this:

def simulate(self):
    my_update_function(self.x,self.y)

so that my_update_function communicates the updated parameter values to the class without having to explicitly store them as outputs.

Please let me know if it is not clear what I mean, and I shall update the question.


Solution

  • def my_update_function(obj):
        obj.x, obj.y = obj.x * obj.x, obj.y * obj.y
    

    then in your class:

    class my_class(object):
        def __init__(self):
            self.x = 2
            self.y = 3
        def simulate(self):
            my_update_function(self)