是否可以访问另一个函数中的局部变量? [英] Is it possible to access a local variable in another function?
问题描述
目标:需要在另一个函数中使用局部变量.这在 Python 中可行吗?
Goal: Need to use local variable in another function. Is that possible in Python?
我想在其他函数中使用局部变量.因为在我的情况下,我需要使用计数器来查看发生的连接数和释放的连接数/为此我正在维护一个计数器.为了实现这一点,我在另一个函数中编写了用于计数和返回局部变量的示例代码.
I would like to use the local variable in some other function. Because in my case I need to use a counter to see the number of connections happening and number of connections releasing/ For that I am maintaining a counter. To implement that I have written sample code for count and returning local variable in another function.
我如何打印 t
&my_reply
在 test()
函数中?
How can I print t
& my_reply
in the test()
function?
代码:counter_glob.py
Code: counter_glob.py
my_test = 0
t = 0
def test():
print("I: ",t)
print("IIIIIIII: ",my_reply)
def my():
global t
reply = foo()
t = reply
print("reply:",reply)
print("ttttt:",t)
def foo():
global my_test
my_test1 = 0
my_test += 1
print my_test1
my_test1 = my_test
my_test += 1
print("my_test:",my_test1)
return my_test1
my()
结果:
> $ python counter_glob.py
0
('my_test:', 1)
('reply:', 1)
('ttttt:', 1)
推荐答案
有多种方法可以访问函数的局部作用域.如果需要,您可以通过调用 locals()
返回整个本地范围,这将为您提供函数的整个本地范围,保存本地范围是不典型的.对于你的函数,你可以在函数本身中保存你需要的变量,func.var = value
:
There are different ways to access the local scope of a function. You can return the whole local scope if you want by calling locals()
this will give you the entire local scope of a function, it's atypical to save the local scope. For your functions you can save the variables that you need in the function itself, func.var = value
:
def test():
print("I: ", my.t)
print("IIIIIIII: ", my.reply)
def my():
my.reply = foo()
my.t = m.reply
print("reply:", my.reply)
print("ttttt:", my.t)
您现在可以正常访问t
和reply
.每次调用函数 my
和 reply
都会更新,foo
返回的任何内容都将分配给 my.reply
.
You can now access t
and reply
normally. Each time you call your function my
and reply
will be updated, whatever foo
returns will be assigned to my.reply
.
这篇关于是否可以访问另一个函数中的局部变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!