Python Dictionary Not Returning New Value Like I Wanted

瘦欲@ 提交于 2019-12-11 19:19:48

问题


So clearly Im doing something wrong. Im a new python/noob coder so it may be obvious for many of you but Im not sure what to do.

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')

So basically you run this and it sets a bunch of default values. It will ask a name, and you give it user input, and it sets the Name key to the new value of your input. They it is suppose to take that new key:value or name:(userinput) and use it in the next little sentence. But instead its going back and using the default value of 'jimmy'.

What do I need to do?


回答1:


The line:

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

is executed when you create the class, not when you later print it. When you create the class, self.herodict['Name'] is set to 'Jimmy'.

You'll have to do the interpolation later on, when you actually have a name. Perhaps you need to use callables instead, like lambda objects:

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'],
}

then call them passing in self later on:

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


来源:https://stackoverflow.com/questions/16844658/python-dictionary-not-returning-new-value-like-i-wanted

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!