From a file foo.py , I want to change the value of a variable which's placed in a different file, let's say bar.py .
I've tried to do it importing the variable, but it seems that it's imported not as reference.
Just examples:
bar.py :
age = 18
foo.py :
from bar import age
def changeAge(age, newAge):
age = newAge
changeAge(age, 19)
I've also tried to pass age
as parameter from bar.py , but same result, it's not passed by reference so its value is not changed.
bar.py :
from foo import changeAge
age = 18
changeAge(age, 19)
As I said, it didn't work at all. I know I can reach this returning the var from the function, but it will probable make me to change a lot of code and, why not, I want to know if there is a way to do what I need, I'm still a beginner in Python. Another way is to wrapper the variable in an object, a list or something like that, but it doesn't seem too elegant.
def changeAge(newAge):
import bar
bar.age = newAge
If you just want to change the value of 'age' you can do the following
age = 18
import bar
def changeAge(newAge):
bar.age = newAge
changeAge(19)
You forgot to return newAge.
from bar import age
def changeAge(age, newAge):
age = newAge
return newAge
print changeAge(age, 19)
Prints out 19 as expected.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.