【问题标题】:Better Method in Python to Call Changed Dict Values Than This?Python 中调用更改的字典值的方法比这更好吗?
【发布时间】:2013-06-01 01:42:51
【问题描述】:
class hero():

    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 thine class? " % self.herodict['Name'],
            "AskWeapon": "A %s ? What shalt thy weapon be? " % self.herodict['Class'],
        }

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



h = hero("Tommy", "Mage", "Staff")
h.setHeroDict("Welcome", "Name")
h.setHeroDict("AskClass", "Class")

好吧,我在here 之前问过这个问题,一个聪明的人告诉我尝试使用 lambdas。我试过了,它奏效了。伟大的!但是我的问题有点不同。正如我在那里所说,我对此很陌生,并且我的知识中有很多我试图填补的漏洞。基本上..我如何在不使用 lambdas 的情况下做得更好(或者人们通常为此使用 lambdas 吗?)

我想做什么:

  1. 有一个带有一些变量的英雄类,这些变量有一些默认值 附在他们身上。
  2. 然后我想使用一个可以去使用我的herotext 的定义 使用其中一个值提出问题。
  3. 然后用户回答问题,然后防御继续 更改herodict 中的相应值

我试图通过的问题: 在我的herotext 中,我有一个值,它本身指向herodict 中的一个键。如链接中所述,我了解到这是由于 herodictherotext 在用户可以提供输入之前被初始化为默认值。因此,它会打印出默认的(在本例中为 Tommy)名称,而不是“AskClass”self.herodict['Name'] 值中的新用户输入名称。

我该如何解决这个问题?我不介意我是否必须制作另一个文件或其他什么,我只想知道做这种事情的更合乎逻辑的方式是什么?我整天都被困在这上面,我的想法是朋友。我知道这对你们很多人来说可能很简单,我希望你能分享你的知识。

谢谢

【问题讨论】:

    标签: python initialization definition


    【解决方案1】:

    给你。这是一种非常干净的方法。很快,我将发布我的课程版本。 :-)(好吧,我本来打算,但这已经很冗长了..)

    class hero():
        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 {Name}. What is thine class? ",
                "AskWeapon": "A {Class}? What shalt thy weapon be? ",
            }
    
        def setHeroDict(self, textkey, herokey):
            n = raw_input(self.herotext[textkey].format(**self.herodict))
            self.herodict[herokey] = n
            print self.herodict[herokey]
    
    
    h = hero("Tommy", "Mage", "Staff")
    h.setHeroDict("Welcome", "Name")
    h.setHeroDict("AskClass", "Class")
    

    解释:

    'format' 只是一个关于 % 所做的新事物。上面的行也可以使用 % 方法。这两个是等价的:

    "Hello, {foo}".format(**{'foo': 'bar'})
    "Hello, %(foo)s!" % {'foo': 'bar'}
    

    无论哪种方式,我们的想法都是避免覆盖您的模板字符串。在您创建字符串模板时,您正在使用它们,然后将值分配给变量。

    就像 5 * 10 总是被 50 替换一样,'meow%s' % 'meow!'总是替换为“喵喵!”。五、十和两种喵喵声都会自动被垃圾回收,除非在其他地方引用它们。

    >>> print 5 * 10
    50
    >>> # the five, ten, and the 50 are now gone.
    >>> template = "meow {}"
    >>> template.format('splat!')
    'meow splat!'
    >>> # 'splat!' and 'meow splat!' are both gone, but your template still exists.
    >>> template
    'meow {}'
    >>> template = template % 'hiss!'  # this evaluates to "template = 'meow hiss!'"
    >>> template  # our template is now gone, replaced with 'meow hiss!' 
    'meow hiss!'
    

    ..so,将您的模板存储在一个变量中,并且不要使用您使用它们创建的字符串“保存”它们,除非您已完成模板并且这样做是有意义的。

    【讨论】:

    • 所以这基本上,从本质上讲,重新初始化了 dict 条目并检索了最新版本?这看起来很不错。这通常是人们进行 dict 更改/重审的方式吗?顺便说一句,感谢您在此答案中所做的努力。如果我能更多地支持你,我会的。 ps, {foo} 方法而不是 % 让我大吃一惊。轻松多了。
    • ..reinitialize 可能不是正确的术语,但是是的。这不是从字典中检索项目的唯一方法,但其中一些是不同的用例,其中一些是个人喜好。我将对其进行编辑以添加我的课程版本。
    • ..好吧,我被打断了,所以,别这样。无论如何,格式需要关键字参数,所以最基本的版本是"{a}, {b}".format(a='1', bar='2')。我也可以制作一个字典,并使用**some_dict 扩展魔法将该字典用作关键字参数:"{a}, {b}".format(**{'a': 1, 'b': 2, 'c': 3})。 Format 会忽略额外的关键字参数,因此可以在其中包含“c”。并非所有功能/方法都忽略附加功能。此外,使用非常大的 dict 会扩展 所有 选项,因此请记住,具有 1000 个键的 dict 会扩展为 1000 个关键字参数,这是非常低效的。
    【解决方案2】:

    您需要使用字典吗?我认为如果你使用简单的类变量会更直接。

    class Hero:
    def __init__(self, name = "Jimmy", prof = "Warrior", weapon="Sword"):
        self.name = name
        self.prof = prof
        self.weapon = weapon
    

    然后使用单独的函数向用户询问信息。

    def create_hero():
        name = input("Greetings, hero. What is thine name? ")
        prof = input("A fine name %s. What is thine class?" % name)
        weapon = input("A %s ? What shalt thy weapon be?" % prof)
        return hero(name, prof, weapon)
    

    使用h = create_hero()运行它

    字典通常用于与关联列表(即一组对)具有相同样式的数据。

    【讨论】:

    • 我认为使用字典存储用户数据是有意义的。它很容易序列化,在保存游戏或类似的东西时很好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-25
    • 2014-10-28
    • 2011-05-17
    • 2015-02-08
    • 1970-01-01
    相关资源
    最近更新 更多