加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

具有默认值的python模板

发布时间:2020-12-16 22:27:06 所属栏目:Python 来源:网络整理
导读:在python中我可以使用模板 from string import Templatetempl = Template('hello ${name}')print templ.substitute(name='world') 如何在模板中定义默认值? 并且没有任何价值地调用模板. print templ.substitute() 编辑 当我没有参数调用时获取默认值,例如

在python中我可以使用模板

from string import Template
templ = 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 Template
defaults = { "name": "default" }
templ = Template('hello ${name}')
print templ.substitute(defaults)               # prints hello default
print templ.substitute(defaults,name="world") # prints hello world

这也适用于safe_substitute:

print templ.safe_substitute()                       # prints hello ${name}
print templ.safe_substitute(defaults)               # prints hello default
print 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()

虽然我发现这不仅仅是将默认值的映射传递给替换,因此不那么明确且不易读.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读