2014-02-11 49 views
0

下面找到的代碼已縮短,因此您不必通讀整個代碼。我提供了一些我覺得需要的代碼才能解決我的問題。爲什麼變量不能傳遞到新類中

因此,這裏是我的一類:

class Terminal(Pane): 

    def setText(self, text): 
     self.text = text 
     self.text_changed = True 
     mac = "bobbyli" 
     Application.monitorInput(mac) 

下面是其他類:

class Application(Terminal): 

    def monitorInput(self, text): 

      clock = pygame.time.Clock() 

      RUNNING = True 
      while RUNNING: 

       for event in pygame.event.get(): 

        if event.type == pygame.QUIT: 
         RUNNING = False 
         break 

        if event.type == pygame.KEYDOWN: 
         if event.key == pygame.K_ESCAPE: 
          self.show_keyboard = not self.show_keyboard 
          self.show_panes = not self.show_panes 

        if event.type == pygame.MOUSEBUTTONUP: 

         #took away bits you didn't need 

         elif textSelected == "OK": 
          with open("setPhrases.txt", 'r') as infile: 
           data = infile.read() 
           print(data) 
          print("Bob") 
          print(text) 
          print("Bob") 

          self.deletePanes() 
          self.createPhrases() 



         # --- draws terminal to reflect the additions --- 
         if self.show_terminal: 
          self.terminal.draw() 

      self.close() 

那麼這就是我如何運行代碼:

myApp = Application() 

#start the monitoring of events on screen 
myApp.monitorInput('') 

所以我的問題是,每當我嘗試通過macApplication,並嘗試從該行的代碼打印出來,我結束了打印Bob\n (empty space)\n Bob

elif textSelected == "OK": 
    with open("setPhrases.txt", 'r') as infile: 
     data = infile.read() 
     print(data) 
    print("Bob") 
    print(text) 
    print("Bob") 

    self.deletePanes() 
    self.createPhrases() 

爲什麼沒有突入text。我究竟做錯了什麼?請幫我解決這個問題。我真的不知道我做錯了什麼。我以前在我的代碼的另一部分完成了這項工作,它工作正常,但我相信我必須做出與代碼的該部分相比錯誤/不同的部分。

回答

0

一旦您撥打myApp.monitorInput(''),方法Application.monitorInput的本地變量text被設置爲''並且永遠不會改變。對monitorInput的後續調用只是重新運行相同的功能(在不同的框架上使用不同的本地語言),但如果第一個仍在運行(由於循環),則在第一個方法text內仍爲''

順便提一句Application.monitorInput(mac)應該引發錯誤,因爲它會丟失一個位置參數(因爲它在類上運行而不是在實例上運行,因此self未被綁定)。

爲了說明這一點:

class Application: 
    def monitorInput(self, text): 
     print ('here be dragons') 

myApp = Application() 
myApp.monitorInput ('bobby') 
Application.monitorInput ('bobby') #exception here 

引發:

Traceback (most recent call last): 
    File "./amt.py", line 9, in <module> 
    Application.monitorInput ('bobby') 
TypeError: monitorInput() missing 1 required positional argument: 'text' 
相關問題