【发布时间】:2019-11-07 04:01:32
【问题描述】:
为简化起见,我指的是 HTML 代码,尽管它有所不同。
我使用装饰器来生成这样的代码。
我必须通过缩进来格式化输出。 我认为我需要跟踪嵌套级别以适应缩进,但我不知道是否以及如何跟踪嵌套级别。 举个例子(https://www.thecodeship.com/patterns/guide-to-python-function-decorators/)
def p_decorate(func):
def func_wrapper(name):
return "<p>{0}</p>".format(func(name))
return func_wrapper
def strong_decorate(func):
def func_wrapper(name):
return "<strong>{0}</strong>".format(func(name))
return func_wrapper
def div_decorate(func):
def func_wrapper(name):
return "<div>{0}</div>".format(func(name))
return func_wrapper
get_text = div_decorate(p_decorate(strong_decorate(get_text)))
@div_decorate
@p_decorate
@strong_decorate
def get_text(name):
return "lorem ipsum, {0} dolor sit amet".format(name)
print(get_text("John"))
# Outputs <div><p><strong>lorem ipsum, John dolor sit amet</strong></p></div>
我想使用通用算法获得,
<div>
<p>
<strong>lorem ipsum, John dolor sit amet</strong>
</p>
</div>
有可能吗?以及如何?
我有一个代码,但它很长。
编辑:由于人们在这里要求提供真实示例,因此您得到了我想要获得的输出
config vdom
edit <vdom>
config router static
edit <number>
set dst <ip> <netmask>
set gateway <ip>
set device <intf>
next
end
end
谢谢,
【问题讨论】:
-
请显示一些代码
-
请edit你的问题和一些例子来说明你的意思。为什么要跟踪嵌套级别和装饰器的外观?
-
你试过elementtree吗? docs.python.org/3/library/xml.etree.elementtree.html,这就是你所需要的。
-
为什么要使用装饰器?你把这个问题复杂化了
-
那么展示一个例子,看看它们是什么样子的?那里有很多配置解析库
标签: python nested decorator nested-forms