简体   繁体   中英

Start and stop functions python

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

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.

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

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