0

I have a loop function that should only run when the variable dd is set to 1. I have two other classes that should start and stop it. Start() sets dd to 1 and runs the loop. Stop() sets dd to 0. But the problem is the variable doesn't change from it's original value 0 when Start() is ran or vise-versa if set to 1 to start with.

  class Class1(object):

      def Function(self, a):
          print a

      def startProgram(self):
          with open('data\blah.txt') as e:
              for i in e:
                  if dd == 1:
                      self.Function(i)

      def Start(self):
          dd = 1
          self.startProgram()

      def Stop(self):
         dd = 0
  • Is `dd` supposed to be an instance variable? Currently it's a local variable in each method – Eric Renouf Dec 16 '15 at 23:35
  • Following up from what Eric said, changing `dd` to `self.dd` everywhere would solve your problem. However, at no point do you set `dd` to 0 other than in the `Stop()` method, which is never called. – Reti43 Dec 16 '15 at 23:38

2 Answers2

1

Besides the problem that there are two dd variables, one in each method, I dont quite understand how you are able to even call Stop while startProgram is being executed?

It looks to me like you are trying to implement a thread:

class Class1(threading.Thread):
    def __init__(self):
        super(Class1, self).__init__()
        self.dd = True

    def function(self, a):
        print a

    def run(self):
        with open('data\blah.txt') as e:
            for i in e:
                if self.dd:
                    self.function(i)
                # maybe else: break?

    def stop(self):
       self.dd = False

EDIT:

You would use it as:

c = Class1()
c.start()
#...
c.stop()
c.join()
zvone
  • 18,045
  • 3
  • 49
  • 77
  • This is only a small part of my code. Well not exact but it's still the same concept. I have the start and stop functions set to run when a button is pressed in the GUI. – Unknown 0.o Dec 16 '15 at 23:49
  • I guess you will be able to use something out of this either way ;) – zvone Dec 16 '15 at 23:51
0

It seems like you want your class Class1 to have the varible dd which would either be set to 1 or 0. To do this you need to use self.dd.

Take a look at this post. It does a great job explaining how variable are assigned in Python.

Community
  • 1
  • 1
M. Bloom
  • 43
  • 7