私の質問はタイトルにあり、次の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の問題は解決されません。
本当に 'task.LoopingCall'行にインデントしていますか? – FamousJameous
@FamousJameousはい、正しい字下げです。それは定義の外にあるので、私は問題にぶつかっているのですが、それがタイムループの仕組みです。私が定義の中に入れれば、タイマはもはや正しく動作しません。ループを厳密に実行する必要があるため、このメソッドには時間の浮動小数点の問題がないため、このタイマーが必要です。 – user3047917
あなたは 'DudeWheresMyCar'クラスでオブジェクトを作成したことはありません。 「自己」とは何を指すのですか? – Barmar