2016-09-21 26 views
0

所以我的問題是在標題和下面的兩段代碼是我的嘗試圍繞這一點。我試圖在腳本啓動後立即分配變量,然後在特定時間間隔運行循環定義並更新同一變量。我不想使用全球。分配一個類變量,然後重新分配一個定義,而不使用全局的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

相關問題