Python - How Can I Make A Function Parameter Global?
Solution 1:
Between functions this can be achieved with the global
keyword. This approach is usually frowned upon.
n = 0defLSE(value):
global n
n = value
defsecond_func():
global n
print(n)
trying this out:
>>>LSE(5)>>>second_func()
5
If you want to share values between functions, may I suggest encapsulating them in a class?
Solution 2:
"Is there anyways to do the global thing without changing the name? I.e. I want to take my parameter make it a global variable retaining the same name (as opposed to here where value and n are named differently)"
from: How to get the original variable name of variable passed to a function
"You can't. It's evaluated before being passed to the function. All you can do is pass it as a string."
What is doable is you can make your code always use a specific variable name, and within your function, declare it a global variable. That way you wouldnt even need to pass it as a parameter, but it would get affected every time you used the function; example:
def test_function ():
global N
N = N + 1
print (N)
N = 5
test_function()
test_function()
test_function()
6 7 8
Post a Comment for "Python - How Can I Make A Function Parameter Global?"