Otrzymuję ten błąd za każdym razem, gdy próbuję uruchomić tę aplikację w jej obecnym stanie.
TypeError: cannot concatenate "str" and "GameData" objects
Próbuję pobrać obiekt danych z klasy Game (GameData) do przeglądarki z moim HTML. Jest to podklasa GameData (), która jest klasą szablonów.
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"
Są jeszcze inne przedmioty, ale jeśli uda mi się zmusić jednego z nich do pracy, mogę wymyślić resztę. Potrzebuję go, aby dostać się do tego oświadczenia elif zaznaczonego komentarzem.
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)
Stamtąd wiem, co robić. Muszę tylko wiedzieć, jak przekonwertować dane na ciąg znaków, abym mógł je połączyć. Gdyby ktoś mógł pomóc, byłbym wdzięczny. Próbowałem również użyć tablicy dla obiektów, ale to też nie działało dla mnie.
Odpowiedzi:
0 dla odpowiedzi № 1Musisz tylko dołączyć __str__
funkcja w twoim Game(GameData)
klasa.
na przykład.
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
Wtedy po prostu zadzwonisz str(g)
gdzie g
czy Twój Game(GameData)
obiekt