从另一个函数访问函数的变量 [英] Accessing a function's variable from another function

查看:169
本文介绍了从另一个函数访问函数的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

from threading import Thread
import time

def print_k():
    while true:
        if main.k % 2 == 1: # ditto
            print(main.k, "is even.") # <-- my problem is HERE ( Ignore all the other stuff )
        time.sleep(2)

def main():
    k = 1
    while k != 200:
        k += 1
        print k
        time.sleep(0.5)

if __name__ == '__main__':
    Thread(target=print_k).start()
    Thread(target=main).start()

在此脚本中(仅示例,忽略所有实际功能)我试图运行 main ),加起来为200并打印它,并在 print_k 中,我正在打印 main 的变量,k。
我提出了一个异常,不出所料,我想知道如何从一个不同的函数中访问一个单独函数的变量(顺便说一句,它们同时运行,因此是线程模块。)

in this script (example only, ignore all realistic functionality) I am trying to run main(), which adds up to 200 and prints it, and in print_k, i am printing main's variable, k. I have an exception raised, unsurprisingly, and am wondering how i can access a separate function's variable from a different function (they are both running at the same time, by the way, hence the Threading module.)

推荐答案

You can not print main 's变量 k 。局部变量的重点在于它们是局部变量。无论他们是否在同一时间运行都没关系;他们每个人都有自己独立的本地环境。 (事实上​​,如果你调用 main 60次,这60个调用中的每一个都有自己的本地环境。)

You can't print main's variable k. The whole point of local variables is that they're local. It doesn't matter whether they're running at the same time or not; they each have their own separate local environment. (In fact, if you call main 60 times, each of those 60 calls has its own local environment.)

但是你可以做很多事情。

But there are a number of things you can do.

最简单但通常最糟糕的是使用全局变量而不是局部变量。只需在 main 函数顶部添加 global k ,为 k添加一些起始值在顶层(在任何线程启动之前),现在你可以在 print_k 中访问相同的全局变量。

The simplest, but generally worst, is to use global variables instead of local variables. Just add global k to the top of the main function, add some start value for k at the top level (before either thread starts), and you can now access the same global variable inside print_k.

将类中的共享状态和函数绑定在一起,这两个函数都成为可以访问 self.k 的方法,这是一个更好的解决方案。将某种可变持有者传递给 main print_k 也是更好的解决方案。围绕显式消息传递重新设计您的应用程序(例如,在 Queue.Queue

Bundling the shared state and functions up together in a class, where both functions become methods that can access self.k, is a better solution. Passing in some kind of mutable "holder" to both main and print_k is also a better solution. Redesigning your app around explicit message passing (e.g., on a Queue.Queue) is even better.

我会展示如何使用类来完成它:

I'll show how to do it with a class:

class KCounter(object):

    def __init__(self):
        self.k = 0

    def print_k(self):
        while True:
            if self.k % 2 == 1:
                print(self.k, "is even.")
            time.sleep(2)

    def main(self):
        self.k = 1
        while self.k != 200:
            self.k += 1
            print self.k
            time.sleep(0.5)

if __name__ == '__main__':
    kcounter = KCounter()
    Thread(target=kcounter.print_k).start()
    Thread(target=kcounter.main).start()

现在,因为我们使用 self.k ,所以 KCounter insta的属性nce,而不是 k ,一个局部变量,两种方法都可以看到相同的变量。

Now, because we're using self.k, an attribute of the KCounter instance, instead of k, a local variable, both methods see the same variable.

这篇关于从另一个函数访问函数的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆