If you create local variable(s) in a function, and then calls a function with those variable(s) as argument(s). How do you update the value of the variable(s) so it reflects in both functions?
disclosure:
- The called function is a segmented piece of the main body of code for tidiness and reduce code repetition. The called function is only called under conditional circumstances and doesn't necessarily return anything. All it does is some calculation that updates the values of variables passed within the function arguement.
How would you get the values in function 2 to update the same values as in function 1?
Thank you in advance!
for example:
def function_1():
object_1 = 1
object_2 = 2
function_2(object_1, object_2)
print("Original values add up to {}".format(object_1 object_2))
def function_2(object_1, object_2):
object_1 = 1
object_2 = 2
print("Updated values add up to {}".format(object_1 object_2))
if __name__ == '__main__':
function_1()
Updated values add up to 6
Original values add up to 3
CodePudding user response:
If you place them in an object, the reference to that object is passed as argument to the function, if you just pass the value of a variable, it's a copy that's passed as argument. See here for a complete explanation
Try something like:
def function_1():
references = {"object_1": 1, "object_2": 2}
function_2(references)
print("Original values add up to {}".format(references["object_1" references["object_2"]))
def function_2(references):
references["object_1"] = 1
references["object_2"] = 2
This would also work if you replace the dictionary with other types of objects like a list, a class instance or a tuple.
CodePudding user response:
Option 1: return the updated values to the calling function
def function_1():
...
object_1, object_2 = function_2(object_1, object_2)
...
def function_2(object_1, object_2):
...
return object_1, object_2
Option 2: build a data structure in function_1()
(like a dict
for example, or a list
or a custom class) and then pass that as the argument to function_2()
; the changes to the dict
you make inside function_2()
will be reflected in function_1()
, because it is the same dict
, you just passed a reference to the same dict
as argument between functions.
def function_1():
...
data = {'object_1': 1, 'object_2': 2}
function_2(data)
# the variable 'data' contains the changes made in 'function_2()'
print(data)
...
def function_2(data):
# the variable 'data' points to the same dict as in 'function_1()'
data['object_2'] = 55
...
There could be other options I am not thinking of right now, but these 2 are the simpler ones, I think.
CodePudding user response:
In Python all variables are passed by reference, so you don't need to do anything. just run the code.
function_1()
Updated values add up to 6
Original values add up to 3
It works