2016-12-17 44 views
0

每次我嘗試在當前狀態下運行此應用程序時,都會收到此錯誤。將數據對象轉換爲腳本的字符串

TypeError: cannot concatenate 'str' and 'GameData' objects 

我想從我的遊戲(GameData)類的數據對象到我的HTML瀏覽器。它是一個模板類GameData()的子類。

class GameData(object): #This class is the template for the data for each game. 
    def __init__(self): 
     self.title = '' 
     self.genre = '' 
     self.description = '' 
     self.developer = '' 
     self.rating = '' 
     self.image = '' 

class Game(GameData): #Thas class holds all the data for each game. 
    def __init__(self): 
     #object for Castlevania 
     self.castlevania = GameData() 
     self.castlevania.title = 'Castlevania' 
     self.castlevania.genre = 'Action Platformer' 
     self.castlevania.description = 'Released in 1986 in Japan, Castlevania for the NES and Famicom Disc System spawned a series rich in action as well as exploration. This first game was merely a simple platformer but it inspired many changes to the formula over the years and invented the "Metroidvania" genre.' 
     self.castlevania.developer = 'Konami' 
     self.castlevania.rating = '7.5/10' 
     self.castlevania.image = 'images/t_castlevania.png' 

還有其他的對象,但如果我可以讓他們其中一個工作,我可以找出其餘的。我需要它來進入這個elif語句,並用評論來突出顯示。

class MainHandler(webapp2.RequestHandler): 
    def get(self): 
     i = Intro() 
     d = GameData() 
     g = Game() 

     if self.request.GET: 
      page = self.request.GET['page'] 
      if page == 'main_page': 
       self.response.write(i.head + i.main_page + i.main_title + i.main_links) 

      elif page == 'castlevania': #The data needs to go in this concatenation. 
       self.response.write(i.head + i.main_page + i.castlevania + (the data object should go here) + i.main_links) 

從那裏我知道該怎麼做。我只需要知道如何將數據轉換爲字符串,以便將它連接起來。如果任何人都可以幫助,我將不勝感激。另外我嘗試使用一個數組作爲對象,但是這對我也不起作用。

回答

0

你只需要在你的Game(GameData)類中包含__str__函數。

例如。

def __str__(self): 
    # Here you would put whatever logic in terms of returning a string 
    # representation of your game object. Eg: 
    return self.castlevania.title 

然後,你就只需撥打str(g)其中g是您Game(GameData)對象

+0

做一回線爲對象的每一個部分?因爲這是更多的代碼來添加。 –

+0

我還有4個對象。 –

+0

你想要返回什麼?你能具體說明應該進入'(數據對象應該到這裏)'嗎? –