Python字典没有像我想要的那样回归新的价值

时间:2013-05-30 19:46:31

标签: python dictionary self

很明显我做错了什么。我是一个新的python / noob编码器,所以对很多人来说可能很明显,但我不知道该怎么办。

class hero():
    """Lets do some heros shit"""

    def __init__(self, name="Jimmy", prof="Warrior", weapon="Sword"):
        """Constructor for hero"""
        self.name = name
        self.prof = prof
        self.weapon = weapon
        self.herodict = {
            "Name": self.name,
            "Class": self.prof,
            "Weapon": self.weapon
        }
        self.herotext = {
            "Welcome": "Greetings, hero. What is thine name? ",
            "AskClass": "A fine name %s. What is your class? " % self.herodict['Name'],
        }

    def thingy(self, textkey, herokey):
        n = raw_input(self.herotext[textkey])
        self.herodict[herokey] = n

        if self.herodict[herokey] != "":
            print self.herodict[herokey]
        else:
            self.herodict[herokey] = self.name
            print self.herodict[herokey]

    def setHeroName(self):
        self.thingy("Welcome", 'Name')

    def setHeroClass(self):
        self.thingy("AskClass", 'Class')

所以基本上你运行它并设置了一堆默认值。它将询问一个名称,并为其提供用户输入,并将Name键设置为输入的新值。他们假设接受新密钥:值或名称:(userinput)并在下一个小句子中使用它。但它反而使用默认值'jimmy'。

我需要做什么?

1 个答案:

答案 0 :(得分:1)

该行:

 "AskClass": "A fine name %s. What is your class? " % self.herodict['Name'],

在创建类时执行,而不是在以后打印时执行。创建课程时,self.herodict['Name']设置为'Jimmy'

稍后当你确实有一个名字时,你必须进行插值。也许你需要使用callables,比如lambda个对象:

self.herotext = {
    "Welcome": lambda self: "Greetings, hero. What is thine name? ",
    "AskClass": lambda self: "A fine name %s. What is your class? " % self.herodict['Name'],
}

然后打电话给他们稍后传递self

n = raw_input(self.herotext[textkey](self))