【问题标题】:Getting self attributes from a .txt file从 .txt 文件中获取自身属性
【发布时间】: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


    【解决方案1】:

    你在这里不需要eval()(或exec)(它们几乎不应该被使用)-Python 有setattr(),它可以满足你的需求。

    请注意,使用已经存在的数据格式(例如JSON)可能更容易避免手动解析它。

    另外注意,在处理文件时,最好使用上下文管理器,因为它读起来很好,并确保文件关闭,即使出现异常:

    with open(monstercheck, 'r') as monsterchck:
            print monstercheck.next()
            for stat, value in parse(monstercheck):
                setattr(self, stat, value)
    

    显然,您需要在这里进行一些真正的解析。

    【讨论】:

    • 解析不会太棘手。只是一个pre_stat,pre_value = line.split('='),后跟stat = pre_stat.strip()value = ast.literal_eval(pre_value),但json 可能更容易
    • @mgilson 不,但除非输入格式很重要,否则仅使用现有工具可能会更容易。
    • 非常感谢!所以要进一步询问,但是关于 JSON 的一些好的文档在哪里,因为我不熟悉它。格式对我来说并不重要,所以我会研究 JSON。另外,除了不需要手动解析之外,主要优点是什么?再次感谢您的帮助!
    • @PrestonCarpenter 只需谷歌 JSON,它是一种非常流行的简单数据标记语言,并阅读我链接的 Python API 文档,这一切都非常简单,因为 JSON 可以很好地转换为核心 Python 数据结构。跨度>
    • 非常感谢,感谢您的帮助。
    【解决方案2】:

    正如@Lattyware 所述,您确实应该为此使用setattr。我将简单地讨论为什么代码会引发错误。 eval 不起作用的原因是因为它评估表达式并且赋值不是表达式。换句话说,你传递给eval 的应该只是等式的右边:

    eval("a = 5")
    

    这和你的代码一样失败。

    您可以从使用eval 更改为exec

    exec "a = 5"  #exec("a = 5") on py3k
    

    但这又是不明智的做法。

    【讨论】:

    • 谢谢你的解释,我一定会记住的。
    猜你喜欢
    • 2015-06-18
    • 1970-01-01
    • 2013-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多