将数据对象转换为脚本的字符串

时间:2016-12-17 00:54:16

标签: python string object concatenation

每次尝试以当前状态运行此应用时,我都会收到此错误。

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

我正在尝试使用我的html将我的Game(GameData)类中的数据对象添加到浏览器中。它是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)

从那里我知道该怎么做。我只需要知道如何将数据转换为字符串,以便我可以连接它。如果有人可以提供帮助,我会很感激。此外,我尝试使用数组作为对象,但这对我来说也不起作用。

1 个答案:

答案 0 :(得分:0)

您只需在__str__课程中加入Game(GameData)功能。

例如

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)对象