存储在dict中时,"稍后"评估字符串生成语句

Sch*_*ote 1 python dictionary python-3.x

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

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

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
...
Run Code Online (Sandbox Code Playgroud)

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

Mar*_*ers 5

是的,使用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)
Run Code Online (Sandbox Code Playgroud)

通过self作为第一个位置参数传入,您可以解决格式化占位符self中的任何属性{...}.

您可以对值应用更详细的格式(例如浮点精度,填充,对齐等),请参阅格式化语法.

演示:

>>> 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'
Run Code Online (Sandbox Code Playgroud)