Python - 如何使函数参数成为全局参数?
Python - How can I make a function parameter global?
例如,我想调用一个函数LSE(n)。
一旦我调用 LSE(5),我希望 n 可以像 5 一样被其他函数调用。我尝试将访问 n 的其他函数嵌套在 LSE 中,但它也无法访问 n。
在函数之间可以使用 global
关键字来实现。这种方法通常不受欢迎。
n = 0
def LSE(value):
global n
n = value
def second_func():
global n
print(n)
尝试一下:
>>> LSE(5)
>>> second_func()
5
如果您想在函数之间共享值,我可以建议将它们封装在 class 中吗?
"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)"
来自: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."
可行的是,您可以让您的代码始终使用特定的变量名,并在您的函数中将其声明为全局变量。这样你甚至不需要将它作为参数传递,但每次你使用该函数时它都会受到影响;示例:
def test_function ():
global N
N = N + 1
print (N)
N = 5
test_function()
test_function()
test_function()
6
7
8
例如,我想调用一个函数LSE(n)。 一旦我调用 LSE(5),我希望 n 可以像 5 一样被其他函数调用。我尝试将访问 n 的其他函数嵌套在 LSE 中,但它也无法访问 n。
在函数之间可以使用 global
关键字来实现。这种方法通常不受欢迎。
n = 0
def LSE(value):
global n
n = value
def second_func():
global n
print(n)
尝试一下:
>>> LSE(5)
>>> second_func()
5
如果您想在函数之间共享值,我可以建议将它们封装在 class 中吗?
"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)"
来自: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."
可行的是,您可以让您的代码始终使用特定的变量名,并在您的函数中将其声明为全局变量。这样你甚至不需要将它作为参数传递,但每次你使用该函数时它都会受到影响;示例:
def test_function ():
global N
N = N + 1
print (N)
N = 5
test_function()
test_function()
test_function()
6 7 8