0

python pass by value and pass by pointer;change value of variable when calling function;

i want to change value of a variable like below c++ code in python is it any way ? void fun(int *anyint) { *anyint = 200; } int main(){ int var=100; cout<<"var before fun call "<<var<<endl; //o/p=>var=100 fun(&var); cout<<"var after fun call "<<var<<endl; //o/p=>var=200 } ----------------------------------- in python i didnt find any way to perform like above c++ code var = 100 def fun(anyvar): anyvar = 200 print("anyvar value inside fun ",anyvar) print("var value before fun call ",var) fun(var) print("var value after fun call ",var) i want to change the value of variable 'var' when calling the function 'fun()'; variable name 'var' is not fixed it may vary .is it any way? i'm new to Python ; Thanks in advance

30th Jan 2021, 7:27 PM
Akshay
Akshay - avatar
4 Respostas
30th Jan 2021, 7:36 PM
Avinesh
Avinesh - avatar
+ 1
you cannot pass variable by reference if they hold basic types... however that's what's done for objects (and you must explicitly clone object to mimic passing by value) so: def fun(anyvar): anyvar = 200 val = 100 print(val) # 100 fun(val) print(val) # 100 but: def objfun(anyvar): anyvar['prop'] = 200 obj = {'prop':100} print(obj) # {'prop':100} objfun(obj) print(obj) # {'prop':200} anyway assigning the fun/objfun local variable won't work in both... but you could workaround by wrapping target variable inside a dict (used as namespace), and have this kind of function: def dictfun(anydict,prop): anydict[prop] = 200 and call it as: dct = { val: 100 } dictfun(dct,'val')
30th Jan 2021, 8:08 PM
visph
visph - avatar
0
Avinesh thanks for your answer;but one problem sometimes we dont know the variable name passing;so the variable name var maybe anothor;that situation global keyword has no use;
30th Jan 2021, 8:20 PM
Akshay
Akshay - avatar
0
visph thanks for the reply.
31st Jan 2021, 7:11 AM
Akshay
Akshay - avatar