Convert Data Objects to Strings for Script - python

I am getting this error each time I try to run this app in its present state.
TypeError: cannot concatenate 'str' and 'GameData' objects
I am trying to get a data object from my Game(GameData) class onto the browser with my html. It's a subclass of GameData() which is a template class.
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'
There are other objects but if I can get one of them to work I can figure out the rest. I need it to get into this elif statement highlighted with a comment.
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)
From there I know what to do. I just need to know how to convert the data into a string so I can concatenate it. If anyone can help I would appreciate it. Also I tried using an array for the objects but that didn't work for me either.

You just need to include the __str__ function in your Game(GameData) class.
eg.
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
Then, you would simply call str(g) where g is your Game(GameData) object

Related

How can I recreate a class object for testing, tried debugging and printing relevant items but can't get it?

I have the following class:
class MessageContext:
def __init__(self, raw_packet, packet_header, message_header, message_index):
self.raw_packet = raw_packet
self.pkthdr = packet_header
self.msghdr = message_header
self.msgidx = message_index
self.msg_seqno = packet_header.seqno + message_index
And a function that creates objects using the above class:
def parsers(data):
...
context = MessageContext(None, PacketAdapter(), msghdr, 0)
self.on_message(rawmsg, context)
I am trying to recreate context, and when i set a breakpoint just after it and print context, I get:
<exchanges.protocols.blahblah.MessageContext object at 0x7337211520>
I have left out quite a bit of code as it is very long, but if any more information is needed I am happy to provide of course.
Here is what I get when I print the arguments of MessageContext:
print(PacketAdapter()) -> <exchanges.blahblah.PacketAdapter object at 0x7f60929e1820>
Following the comments below, the PacketAdapter() class looks like this:
class PacketAdapter:
def __init__(self):
self.seqno = 0

Python PNL OOP, how to use attribute from another class

I am planning to design a program to track profit and loss of my stock account, then I used Python and hope to solve it in a Object Oriented way.
Code:
class PNL(object):
stock_amount = {}
def __init__(self,cash,position):
self.cash = cash
self.position = position
def buy(self,Stock,amount):
pass
def sell(self,Stock,amount):
pass
def stock_amt(self,Stock):
if Stock().symbol not in stock_amount:
stock_amount[Stock().symbol] = 0
else:
return stock_amount
class Stock():
def __init__(self,symbol,timestamp,price):
self.symbol = symbol
self.time = timestamp
self.price = price
a = PNL(0,0)
APPL = []
APPL.append(Stock('APPL',0,10))
APPL.append(Stock('APPL',1,12))
a.stock_amt('APPL')
for stock in APPL:
if stock.time == 0:
print stock.price
But this doesn't work fine, anyone has idea on that?
Firstly you need to fix the class PNL, when you declare the methods with Stock, as its an argument/parameter, you'd better choose another name, or write it in lowercase to make difference with the class Stock.
Just think you will give an instance to these methods, no need to write the type, and by the way, no need to instantiate again the class inside the method by doing Stock().symbol, you'll give an instance, or directly the attribute symbol if you prefer.
Also, the stock_amount can be stored as a instance attribute, as below :
class PNL(object):
def __init__(self,cash,position):
self.cash = cash
self.position = position
self.stock_amount = {}
def buy(self,stock,amount):
pass
def sell(self,stock,amount):
pass
def stock_amt(self,stock):
if stock.symbol not in self.stock_amount:
self.stock_amount[stock.symbol] = 0
else:
return self.stock_amount
Then when you call your classes, i think you wanted to loop on the list APPL you've built (then just call a.stock_amt(stock_object_created) :
a = PNL(0,0)
APPL = []
APPL.append(Stock('APPL1',0,10))
APPL.append(Stock('APPL2',1,12))
for stock in APPL:
a.stock_amt(stock)
if stock.time == 0:
print stock.price
print a.stock_amount
#>>>10
#>>>{'APPL2': 0, 'APPL1': 0}

Python: Define Object within a Class

Very new to Python and could do with some help. How do I go about referencing members in a class?
I have two csv files. One contains a series of parts and associated material ID. The other is a material index that contains materials ID's and some information about that material.
My intention is to create a third file that contains all of the parts, their material Id's and the information if present in the material index.
I have created a class for the material index and am trying to access objects in this class using material Ids from the part file however, this is not working and I am unsure as to why. Any help is appreciated:
class material():
def __init__(self, name, ftu, e, nu):
self.name = name
self.ftu = ftu
self.e = e
self.nu = nu
def extract_FTU_Strain(input_file_parts,input_file_FTU,output_file):
parts = {}
materials = {}
for aline in open(input_file_FTU, 'r'):
comma_split = aline.strip().split(',')
name = comma_split[1]
ftu = comma_split[8]
e = comma_split[9]
nu = comma_split[7]
try:
materials[int(comma_split[0])] = material(comma_split[1],comma_split[8],comma_split[9],comma_split[7])
#materials[comma_split[0]] = material(comma_split[1],comma_split[8],comma_split[9],comma_split[7])
except:
pass
for i in open(input_file_parts, 'r'):
semicolon_split = i.strip().split(';')
material_id = semicolon_split[3]
part = semicolon_split[0]
part_id = semicolon_split[1]
material_name = materials[material_id].name
FTU = materials[material_id].ftu
Stress = materials[material_id].e
output.write(','.join([part,part_id,material_name,material_id,FTU,Stress]) + '\n')
output = open (output_file,'w')
output.write('Part Title, Part Id, Material Id, FTU, e' + '\n')
output.close()
import sys
input_file_parts = '/parttable.csv'
input_file_FTU = '/Material_Index.csv'
output_file = '/PYTHONTESTING123.csv'
extract_FTU_Strain(input_file_parts,input_file_FTU,output_file)
Since in the comments you said your error is in materials[material_id] make material_id an integer as it was an integer when you created the object.
You created it this way
materials[int(comma_split[0])]=...
But later called it without converting material_id to an int. Do this before calling it in your for loop to write in the output.
material_id = int(material_id)
I may have misinterpreted your question, but going off the line 'How do I go about referencing members in a class?' you can reference member variables like so:
class Demonstration:
def __init__(self, a, b):
self.a = a
self.b = b
def printMembers(self):
print self.a, self.b
So inside the class you can use self.someVariable to reference member variables.
If you want to access them outside of the class:
myclass.myvariable
I'll happily edit the answer if I have't quite understood your question or if there is a specific error you are getting.
I did not understand what error you have, could you put the traceback? Anyway, you are creating a class instance at the time of assignment. For more elegant programming, you could simply do:
m = materials(name, ftu, e, nu)
This way you can access the instance variables like this:
m.name
m.ftu
...
And try, except -> pass it's very dangerous

Python Object Declaration Is Not Working

I really hope this is not a repeat...if it is, I can't find an answer anywhere, so I apologize.
Anyways, my question is, I'm writing code where, if the data I get requires a team instead of a player, I have a class (called Team) that holds two SinglePlayers (also a class), and then a few other attributes, just strings. The problem is, when I iterate through my loop, reading the xml data and filling up my "team" variable, it seems that all the info for the SinglePlayers doesn't get reset. This is a problem, because it is is changing that info every time I insert a new "team" into the list of "team" objects I have. The code is long, so I'm only going to post what's relevant.
I have only been working with python again for a few days. I have been working the past year in java and c++ so my brain has those concepts in my head of how variables and structures work. I know python is different, so if someone could please clarify why this doesn't work, that would be amazing. Thanks!
class SinglePlayer:
entry_code = ""
first_name = ""
last_name = ""
nation = ""
seed_rank_sgl = ""
seed_rank_dbl = ""
entry_rank_sgl = ""
entry_rank_dbl = ""
class Team:
top_player = SinglePlayer()
bottom_player = SinglePlayer()
entry_code = ""
seed_rank = ""
entry_rank = ""
def DoublesEvent(self, team_nodes):
#Create List to store team objects
teams_list = []
for k in range(0, team_nodes.length):
#Get the current node
teams_node = team_nodes.item(k)
team_node = team_nodes.item(k).getElementsByTagName("Player")
top_player_node = team_node.item(0)
bottom_player_node = team_node.item(1)
#Make a new team object to fill and add to teams_list
team = Team()
team.entry_code = teams_node.getAttribute("EntryCode")
#Top Player Info
team.top_player.first_name = top_player_node.getAttribute("FirstName")
team.top_player.last_name = top_player_node.getAttribute("LastName")
team.top_player.nation = top_player_node.getAttribute("Nation")
#Bottom Player Info
team.bottom_player.first_name = bottom_player_node.getAttribute("FirstName")
team.bottom_player.last_name = bottom_player_node.getAttribute("LastName")
team.bottom_player.nation = bottom_player_node.getAttribute("Nation")
eam.seed_rank = self.GetSeedRank(team)
team.entry_rank = self.GetEntryRank(team)
#Add the team to the list
teams_list.append(team)
return teams_list
Your class holds a reference to two SinglePlayer() instances, not your instances. Use a __init__ method to create new instances for every Team instance:
class Team:
entry_code = ""
seed_rank = ""
entry_rank = ""
def __init__(self):
self.top_player = SinglePlayer()
self.bottom_player = SinglePlayer()
As it happens, because you rebind each of the string attributes on the instances you create, you happen to create instance attributes for those. You'd be better off moving those into __init__ as well and making their relationship as instance attributes explicit:
class Team:
def __init__(self):
self.entry_code = ""
self.seed_rank = ""
self.entry_rank = ""
self.top_player = SinglePlayer()
self.bottom_player = SinglePlayer()
and do the same for your SinglePlayer class.

Zelle Graphics interface issue

I'm using Zelle Graphics library and I'm having trouble replacing graphics objects (which, in this case, happens to be text objects).
Here's the code:
from Graphics import *
winName = "Window"
win = Window(winName,600,500)
win.setBackground(Color('silver'))
title = Text((300,20),"Zack's Flash Card Maker")
title.draw(win)
p1 = Rectangle((50, 100),(550,400))
p1.setFill(Color("black"))
p1.draw(win)
class FlashCard:
def __init__(self):
self.commands = {'addQuestion':self.addQuestion,'startGame':self.startGame}
self.stack = []
self.questions = {}
self.questionAnswered = False
self.questionsCorrect = 0
self.questionsIncorrect = 0
def addQuestion(self):
question = ' '.join(self.stack)
self.stack = []
answer = input(question)
self.questions[question] = answer
def startGame(self):
for question in self.questions:
if(self.questionAnswered == False):
answer=input(question)
questionText = Text((300,150),question)
questionText.setFill(Color("white"))
questionText.draw(win)
if(answer == self.questions[question]):
questionAnswer = Text((300,200),answer + " is correct!")
questionAnswer.setFill(Color("green"))
questionAnswer.draw(win)
self.questionsCorrect = self.questionsCorrect + 1
continue
else:
questionAnswer = Text((300,200),answer + " is incorrect. Study this one.")
questionAnswer.setFill(Color("red"))
questionAnswer.draw(win)
self.questionsIncorrect = self.questionsIncorrect + 1
continue
def interpret(self,expression):
for token in expression.split():
if token in self.commands:
operator = self.commands[token]
operator()
else:
self.stack.append(token)
i = FlashCard()
i.interpret('What is your dog\'s name? addQuestion')
i.interpret('What is your favorite thing to do? addQuestion')
i.interpret('startGame')
This is essentially a mini flash card program I'm making. It takes the interpret commands at the bottom and executes them based on the dictionary in the FlashCard class. It basically works: it does the correct text objects. However, text begins to overlap other text objects because it re-draws. I've tried moving the .draw function all over, but it either doesn't appear at all or it overlaps.
Anyone have any suggestions? I want the text to replace for each new flashcard question.
Thanks!
there's an undraw() command that you need to use if you want to make something invisible. I'd recommend placing it right before your continue statements. It's used like
questionText.undraw()
questionAnswer.undraw()
Alternatively, you can use the del command to get rid of each questionText/questionAnswer instance when you're done with it. That's probably a better option since you're actually freeing up the memory that way instead of storing data and not doing anything with it.
You can use setText method to change the text.
example:
string = Text(Point(1, 1), 'original string')
sting.setText('new string')

Categories

Resources