Python 当存储在dict中时,对生成字符串的语句“later”求值

Python 当存储在dict中时,对生成字符串的语句“later”求值,python,python-3.x,dictionary,Python,Python 3.x,Dictionary,我有一个AI例程,它将各种数据存储为内存对象。内存对象根据其“内存类型”具有不同的参数,这些参数在retrospect中传递给构造函数,每种类型的内存实际上都应该是内存的一个子类,但目前这并不重要 我需要为Memory-s设置一个str方法。用另一种语言,我可能会这样做: if self.memtype == "Price": return self.good+" is worth "+self.price+" at "+self.location elif self.memtype =

我有一个AI例程,它将各种数据存储为内存对象。内存对象根据其“内存类型”具有不同的参数,这些参数在retrospect中传递给构造函数,每种类型的内存实际上都应该是内存的一个子类,但目前这并不重要

我需要为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
...
但是做这类事情的最快方法是使用dicts。但问题是,这些字符串在返回之前需要插入值。我想这可以通过lambdas实现,但这让我觉得有点不雅观,过于复杂。是否有更好的方法突然想到str.format…?

是的,使用:

通过传入self作为第一个位置参数,可以在{…}格式占位符中寻址self上的任何属性

您可以对值应用更详细的格式设置,如浮点精度、填充、对齐等。也请参见

演示:

是的,使用:

通过传入self作为第一个位置参数,可以在{…}格式占位符中寻址self上的任何属性

您可以对值应用更详细的格式设置,如浮点精度、填充、对齐等。也请参见

演示:

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