【问题标题】:Evaluating a string-producing statement 'later' when stored in a dict当存储在字典中时评估字符串生成语句“稍后”
【发布时间】:2014-01-12 18:48:53
【问题描述】:

我有一个 AI 例程,可以将各种数据存储为 Memory 对象。 Memory 对象根据传递给构造函数的“内存类型”具有不同的参数(回想起来,每种类型的内存确实应该是 Memory 的子类,但目前这并不重要)。

我需要为Memory-s 设置一个__str__() 方法。在另一种语言中,我可能会这样做:

if self.memtype == "Price":
    return self.good+" is worth "+self.price+" at "+self.location
elif self.memtype == "Wormhole":
    return self.fromsys+" has a wormhole to "+self.tosys
...

但是做这种事情的 Pythonic(和快速)方法是使用 dicts。但问题是,这些字符串需要在返回之前插入值。我想这可以用 lambdas 来完成,但这让我觉得有点不优雅和过于复杂。有没有更好的方法(str.format() 突然想到...)?

【问题讨论】:

    标签: python python-3.x dictionary


    【解决方案1】:

    是的,使用str.format()

    formats = {
        'Price': '{0.good} is worth {0.price} at {0.location}',
        'Wormhole': '{0.fromsys} has a wormhole to {0.tosys}',
    }
    
    return formats[self.memtype].format(self)
    

    通过传入self 作为第一个位置参数,您可以在{...} 格式占位符中处理self 上的任何属性。

    您也可以对值应用更详细的格式(例如浮点精度、填充、对齐等),请参阅formatting syntax

    演示:

    >>> class Demo():
    ...     good = 'Spice'
    ...     price = 10
    ...     location = 'Betazed'
    ...     fromsys = 'Arrakis'
    ...     tosys = 'Endor'
    ... 
    >>> formats = {
    ...     'Price': '{0.good} is worth {0.price} at {0.location}',
    ...     'Wormhole': '{0.fromsys} has a wormhole to {0.tosys}',
    ... }
    >>> formats['Price'].format(Demo())
    'Spice is worth 10 at Betazed'
    >>> formats['Wormhole'].format(Demo())
    'Arrakis has a wormhole to Endor'
    

    【讨论】:

      猜你喜欢
      • 2020-01-04
      • 2011-01-18
      • 1970-01-01
      • 2017-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-22
      相关资源
      最近更新 更多