1
    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

1 Answer 1

2

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()
Sign up to request clarification or add additional context in comments.

6 Comments

Yeah,solved. So..Does it mean if I have n functions in a class which all need to access the global var x, I need to declare x as global inside each of these functions?
Why do you need it to be global? can't it be a class variable ? see above
In my program,it has to be. The code above is just a testing code I created with the same pattern of a part of my original code where encounters a problem. In my program var "is_online" is shared by multiple classes.thanks
@user3788871 I'll add another approach in a minute
What you mean in the second method is passing the global variable as a parameter to the class constructor. Are you sure that python passes reference to a function instead of a copy?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.