简体   繁体   English

从另一个函数访问一个函数的变量

[英]Accessing a function's variable from another function

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

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. 在此脚本中(仅作为示例,请忽略所有现实功能),我尝试运行main() ,该print_k并打印200,在print_k ,我打印main的变量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't print main 's variable k . 不能打印main的变量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.) (实际上,如果您拨打main电话60次,则这60个电话中的每个都有其自己的本地环境。)

But there are a number of things you can do. 但是您可以做很多事情。

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 . 只需添加global k到顶部main功能,增加对一些起始值k在顶层(或者线程开始之前),你现在可以访问内部同一个全局变量print_k

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. 将共享状态和函数捆绑在一个类中是一个更好的解决方案,在该类中,两个函数都成为可以访问self.k的方法。 Passing in some kind of mutable "holder" to both main and print_k is also a better solution. 将某种可变的“ holder”传递给mainprint_k也是一个更好的解决方案。 Redesigning your app around explicit message passing (eg, on a Queue.Queue ) is even better. 围绕显式消息传递(例如,在Queue.Queue )重新设计应用程序甚至更好。

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

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. 现在,因为我们使用self.k的的属性KCounter实例,而不是k ,局部变量,两种方法都看到相同的变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM