【问题标题】:Is it possible to access a local variable in another function?是否可以在另一个函数中访问局部变量?
【发布时间】:2016-09-25 02:32:22
【问题描述】:

目标:需要在另一个函数中使用局部变量。这在 Python 中可行吗?

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

如何在test() 函数中打印tmy_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)

【问题讨论】:

  • 不,你不能,这就是“本地”的意思。除此之外,您不会在代码中的任何位置定义任何类型的名为 my_reply 的变量。
  • 在示例代码中,我有一个我的函数,在我的函数中我将回复分配给全局变量。当我在我的函数中打印全局变量时,即 t 。印刷值符合预期。但我不确定为什么在测试功能中它不打印?因为 t 在我的函数中使用回复进行了更新。
  • 在函数my() 中,您将值分配给名为reply 的局部变量,然后将其分配给名为t 的全局变量。在 test() 函数中,您引用了全局变量 t 和另一个名为 my_reply 的函数,它尚未在任何地方定义。 my_reply 不是另一个函数中局部变量 reply 的另一个名称。你不能那样做。您可以在my() 中创建一个函数属性,并在test() 中使用my answer 中显示的技术访问另一个问题。这将允许您定义my.reply

标签: python python-2.7 python-3.x


【解决方案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

【讨论】:

    【解决方案2】:

    据我所知,您无法访问函数外部的局部变量。但在我看来,即使你可以,这也是一种不好的做法。

    为什么不使用函数或类。

    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()))
    

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多