具有默认值的python模板

具有默认值的python模板,第1张

概述在python中我可以使用模板from string import Template templ = Template('hello ${name}') print templ.substitute(name='world') 如何在模板中定义默认值?并且没有任何价值地调用模板.print templ.substitute() 编辑当我没有参数调用时获取默认

在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模板所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1205990.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-04
下一篇 2022-06-04

发表评论

登录后才能评论

评论列表(0条)

保存