在python中我可以使用模板
from string import Templatetempl = Template('hello ${name}')print templ.substitute(name='world')
如何在模板中定义默认值?
并且没有任何价值地调用模板.
print templ.substitute()
编辑
当我没有参数调用时获取默认值,例如
print templ.substitute() >> hello name
最佳答案Template.substitute方法采用mapping
argument in addition to keyword arguments.关键字参数覆盖映射位置参数提供的参数,这使得映射成为实现默认值的自然方式,而无需子类化:from string import Templatedefaults = { "name": "default" }templ = Template('hello ${name}')print templ.substitute(defaults) # prints hello defaultprint templ.substitute(defaults,name="world") # prints hello world
这也适用于safe_substitute:
print templ.safe_substitute() # prints hello ${name}print templ.safe_substitute(defaults) # prints hello defaultprint templ.safe_substitute(defaults,name="world") # prints hello world
如果你绝对坚持不传递任何参数替换你可以继承模板:
class DefaultTemplate(Template): def __init__(self,template,default): self.default = default super(DefaultTemplate,self).__init__(template) def mapPing(self,mapPing): default_mapPing = self.default.copy() default_mapPing.update(mapPing) return default_mapPing def substitute(self,mapPing=None,**kws): return super(DefaultTemplate,self).substitute(self.mapPing(mapPing or {}),**kws) def substitute(self,self).safe_substitute(self.mapPing(mapPing or {}),**kws)
然后像这样使用它:
DefaultTemplate({ "name": "default" }).substitute()
虽然我发现这不仅仅是将默认值的映射传递给替换,因此不那么明确且不易读. 总结
以上是内存溢出为你收集整理的具有默认值的python模板全部内容,希望文章能够帮你解决具有默认值的python模板所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)