About Python global variable

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

    import sys
    from threading import Thread

    is_online=1

    class CommandListenerThread(Thread):
        global is_online
        def run(self):
          while is_online:
             next_command=sys.stdin.readlines();
             if next_command ==  exit :
                 is_online=0
             else:
                 print next_command



    listener=CommandListenerThread()
    listener.start()

When I run this python code,it shows an error: "UnboundLocalError: local variable is_online referenced before assignment"

I tested another code which uses the same way to access the global variable inside a class,and it works fine. So,what is wrong with this specific code?

the code may look weird which using a thread to listen the command line,but it is just a part of my program which gets an error when I run the whole program.

thank you guys

Answers

Move global is_online into run() to solve the error.

To address your other question (in a comment below), why not make it a static class variable ?

class CommandListenerThread(Thread):    
    is_online = 1    
    def run(self):
        print CommandListenerThread.is_online

In case that you have to use another code with a global is_online, you can take the DI (dependency injection) approach as follows:

import sys from threading import Thread

is_online = 2

class CommandListenerThread(Thread):

    def __init__(self, is_online):
        super(CommandListenerThread, self).__init__()       
        CommandListenerThread.is_online = is_online # now it s a static member
                                                    # if you want to make it an instance member use self.is_online

    def run(self):
        print CommandListenerThread.is_online        

listener=CommandListenerThread(is_online) # inject the value to the constructor 
listener.start()

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/25336515/about-python-global-variable

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils