【发布时间】:2012-11-13 15:13:39
【问题描述】:
我正在为 D&D 制作战斗助手。我打算让它以这种格式从 .txt 文件中获取每个怪物的统计信息:
_Name of monster_
HP = 45
AC = 19
Fort = -3
我正在使用一个名为Monster 的类,__init__ 会遍历 .txt 文件。它迭代得很好,我的问题是我不能让变量在它之前有self.。 Monsterfind() 只是找到了怪物 .txt 文件的路径,我知道这不是问题,因为变量打印正常。
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'
它只是说:self.AC = 5SyntaxError: invalid syntax @ the equals sign
如果我的班级或__init__有任何问题,即使不重要,请告诉我,因为这是我第一次使用班级。
提前谢谢你
【问题讨论】:
标签: python class text-files init self