2016-09-25 37 views
0

目标:需要在另一个函数中使用局部变量。在Python中可能吗?是否可以在另一个函数中访问局部变量?

我想在其他一些函数中使用局部变量。因为在我的情况下,我需要使用计数器来查看发生的连接数量和连接数量/为此,我正在维护一个计数器。为了实现这一点,我编写了用于count的示例代码,并在另一个函数中返回局部变量。

如何在test()函数中打印t & my_reply

代码: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) 
+0

不,你不能,那就是“本地”的意思。除此之外,你并没有在你的代码中的任何地方定义一个名为'my_reply'的变量。 – martineau

+0

在示例代码中,我有一个我的函数,在我的函数中,我将分配回复给全局变量。当我在我的函数中打印全局变量时,按预期打印价值。但我不知道为什么在测试功能它不打印?因为t在我的函数中用回复更新。 –

+0

在函数my()中,将一个值赋给一个名为'reply'的局部变量,然后将其赋值给一个名为't'的全局变量。在'test()'函数中,引用't',全局变量和另一个名为'my_reply',它在任何地方都没有定义。 'my_reply'不是另一个函数中局部变量'reply'的另一个名字。你不能那样做。你可以在'my()'中创建一个函数属性,并使用[我的答案](http://stackoverflow.com/a/19327712/355230)中显示的技术在'test()'中访问它。这将允许你定义一个'my.reply'。 – martineau

回答

0

据我所知,你不能让外面的功能访问本地变量。但即使你可以在我看来这将是一个不好的做法。

为什么不使用函数或类。

connections = 0 

def set_connection_number(value): 
    global connections; connections = value; 

def get_connection_number(): 
    global connections; 
    return connections; 

# test 
set_connection_number(10) 
print("Current connections {}".format(get_connection_number())) 
1

有不同的方法来访问函数的本地作用域。如果你想调用locals(),你可以返回整个本地范围,这会给你一个函数的整个局部范围,保存本地范围是非典型的。为了您的功能,你可以保存您在函数本身所需要的变量,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) 

您现在可以访问treply正常。每次您致电您的功能myreply将被更新,无论foo返回将被分配给my.reply

0

除了closure你不会访问你的函数范围之外的本地变量。 如果变量必须在不同的方法之间共享,那么最好使它们像@pavnik所提到的那样全局。

相关问题