简体   繁体   中英

How to reference a class variable in python

I cant seem to get the classes to read the alive dictionary it keeps throwing a NameError: global name 'import_1' is not defined I am using this guide:

http://www.ibiblio.org/g2swap/byteofpython/read/class-and-object-vars.html

Here is the code:

class test_imports:#Test classes remove 
      alive = {'import_1': True, 'import_2': True};

      def halt_listener(self, control_Queue, thread_Name, kill_command):
          global alive
          while True:
              isAlive = control_queue.get()
              if isAlive == kill_command:
                 test_imports.alive[thread_Name] = False;
                 return

      def import_1(self, control_Queue, thread_Number):
          print ("Import_1 number %d started") % thread_Number
          t = Thread(target=test_imports.halt_listener, args=(control_Queue, 'import_1', 't1kill'))
          count = 0 
          global alive 
          run = test_imports.alive[import_1];
          while run:
                print ("Thread type 1 number %d run count %d") % (thread_number, count)
                count = count + 1
                print ("Test Import_1 ", run)
                run = test_Imports.alive['import_1'];
          print ("Killing thread type 1 number %d") % thread_Number 

What am I missing? Thanks guys!

You forgot quotes:

run = test_imports.alive['import_1']

Note that inside class there's no need to use global , secondly inside methods you can use self to refer to the class as well as instance attributes:

run = self.alive['import_1']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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