简体   繁体   中英

Converting a function parameter into Global variable

When I try convert a parameter into global variable it gives the following error. Is there any way where I can convert the imported paramter to global without using two different names? Edit : The solve(grid) will be called by another module. I want to make sure the parameter becomes global after the function being called.

>>> grid = []
>>> def solve(grid)
...     global grid
...

Output:

File "<stdin>", line 1
SyntaxError: name 'grid' is local and global

If you declare the variable as global, It's only "global" inside the function anyway. The Global here doesn't have any effect on other functions. If you want the variable to be callable in other functions you call from this one without passing the value or if yo uhave paralel threads running, don't use global variables.

I don't exactly know what you plan to do, but I would suggest using a class and handling all the using of the variable over getter and setter methods instead. It's not pythonic but should work... You can find more about it here: What's the pythonic way to use getters and setters?

Hope I could point you in the right direction. There are a lot of other better ways to handle scopes of variables than using global. Start with that.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM