I’m making a combat helper for D&D. I plan to make it get the stats of each monster from a .txt file in this format:
_Name of monster_
HP = 45
AC = 19
Fort = -3
I’m using a class called Monster, and __init__ iterates through the .txt file. It iterates fine, my problem is that I can’t get the variables to have self. before it. Monsterfind() simply finds the path to the monster .txt file, and I know that is not the problem, as the variables are printing fine.
class Monster:
def __init__(self, monster):
"""Checks if the monster is defined in the directory.
If it is, sets class attributes to be the monster's as decided in its .txt file"""
self.name = monster.capitalize()
monstercheck = self.monsterfind()
if monstercheck != Fales:
monsterchck = open(monstercheck, 'r')
print monstercheck.next() # Print the _Name of Monsters, so it does not execute
for stat in monstercheck:
print 'self.{}'.format(stat) # This is to check it has the correct .txt file
eval('self.{}'.format(stat))
monstercheck.close()
print 'Monster loaded'
else: # if unfound
print '{} not found, add it?'.format(self.name)
if raw_input('Y/N\n').capitalize() == 'Y':
self.addmonster() # Function that just makes a new file
else:
self.name = 'UNKNOWN'
It just says: self.AC = 5 SyntaxError: invalid syntax @ the equals sign
If there is any problem with my class or my __init__, even if it is unimportant, please tell me as this is the first time I’m using classes.
Thank you in advance
You don’t need
eval()(orexec) here (they should pretty much never be used) – Python hassetattr(), which does what you want.Note that it might be easier to use a data format that already exists, such as JSON, to avoid manually parsing it.
As another note, when working with files, it’s best to use a context manager, as it reads nicely, and ensures a file is closed, even if there is an exception:
Obviously, you would need to do some real parsing here.