【问题标题】:Convert Data Objects to Strings for Script将数据对象转换为脚本的字符串
【发布时间】:2016-12-17 00:54:16
【问题描述】:

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

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)

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

【问题讨论】:

    标签: python string object concatenation


    【解决方案1】:

    您只需在您的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) 对象

    【讨论】:

    • 对象的每个部分都做回线?因为要添加更多代码。
    • 我还有 4 个对象。
    • 您到底想返回什么?你能具体说明(the data object should go here)应该输入什么吗?
    • 这是将 python 对象表示为字符串的常用且建议的方式。
    • 如果我必须这样做,那也没关系。我只是想知道是否有一种方法可以减少代码。不过谢谢。我很感激这些信息。
    猜你喜欢
    • 2019-03-05
    • 2022-01-20
    • 1970-01-01
    • 2014-01-14
    • 2011-08-02
    • 2016-06-10
    相关资源
    最近更新 更多