Assigning a class variable and then reassigning in a definition without using global in Python
<p>So my question is in the title and the following two snippets of code are my attempts around this.  I am trying to assign a variable as soon as the script is started and then just run the loop definition at certain time intervals and update that same variable.  I do not want to use a global.</p>

<pre><code>from twisted.internet import task, reactor

class DudeWheresMyCar(object):
    counter = 20
    stringInit = 'initialized string'

    def loop():
        stringNew = 'this will be updated with a changing string'
        if (stringInit == stringNew):      #Error line
            print(stringNew)
        elif (stringInit != stringNew ):
            stringInit = stringNew
        pass

    task.LoopingCall(loop).start(counter)
    reactor.run()
</code></pre>

<p>This leads to an error undefined stringInit.  I know why I am getting this error so I made an attempt to fix this using the .self variable and the code is below.</p>

<pre><code>from twisted.internet import task, reactor

class DudeWheresMyCar(object):
    counter = 20

    def __init__(self):
        self.stringInit = 'Initialized string'

    def loop(self):
        stringNew = 'this will be updated with a changing string'
        if (self.stringInit == stringNew):
            print(stringNew)
        elif (self.stringInit != stringNew ):
            self.stringInit = stringNew
        pass

    task.LoopingCall(self.loop).start(counter)    #Error line
    reactor.run()
</code></pre>

<p>I get an error that says that self is undefined.  I understand what is causing both scenario's to throw errors but I am not sure how to change my approach to accomplish my goal.  I also ran into using a singleton but that still does not fix the problem in scenario 2.</p>

<p>I think you want a <code>classmethod</code>, and you need to start the the task outside of the class definition. I would expect something like the following code to work</p>

<pre><code>from twisted.internet import task, reactor

class DudeWheresMyCar(object):
    counter = 20

    stringInit = 'Initialized string'

    @classmethod
    def loop(cls):
        stringNew = 'this will be updated with a changing string'
        if (cls.stringInit == stringNew):
            print(stringNew)
        elif (cls.stringInit != stringNew ):
            cls.stringInit = stringNew


task.LoopingCall(DudeWheresMyCar.loop).start(DudeWheresMyCar.counter)
reactor.run()
</code></pre>

python python-3.x