2016-09-21 4 views
0

私の質問はタイトルにあり、次の2つのコードスニペットが私の試みです。私はスクリプトが開始されるとすぐに変数を割り当てようとしていて、特定の時間間隔でループ定義を実行し、同じ変数を更新しています。私はグローバルを使用したくありません。クラス変数を代入し、Pythonでグローバルを使わずに定義に再割り当て

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

これは、エラーundefined stringInitにつながります。私はなぜこのエラーが出るのか知っているので、.self変数を使ってこれを修正しようとしました。コードは以下のとおりです。

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

自己が定義されていないというエラーが表示されます。両方のシナリオにエラーが発生する原因は何かを理解していますが、目標を達成するためにアプローチを変更する方法がわかりません。私もシングルトンを使いましたが、それでもシナリオ2の問題は解決されません。

+0

本当に 'task.LoopingCall'行にインデントしていますか? – FamousJameous

+0

@FamousJameousはい、正しい字下げです。それは定義の外にあるので、私は問題にぶつかっているのですが、それがタイムループの仕組みです。私が定義の中に入れれば、タイマはもはや正しく動作しません。ループを厳密に実行する必要があるため、このメソッドには時間の浮動小数点の問題がないため、このタイマーが必要です。 – user3047917

+1

あなたは 'DudeWheresMyCar'クラスでオブジェクトを作成したことはありません。 「自己」とは何を指すのですか? – Barmar

答えて

1

classmethodと思って、クラス定義の外でタスクを開始する必要があります。

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

ありがとう!これは美しく働いただけでなく、クラス、定義、およびそれらを参照する方法がはるかに理にかなっています。 – user3047917

関連する問題