【发布时间】:2019-11-14 16:40:18
【问题描述】:
为了实现美化xml,我编写了以下代码
def prettify_by_response(response, prettify_func):
root = ET.fromstring(response.content)
return prettify_func(root)
def prettify_by_str(xml_str, prettify_func):
root = ET.fromstring(xml_str)
return prettify_func(root)
def make_pretty_xml(root):
rough_string = ET.tostring(root, "utf-8")
reparsed = minidom.parseString(rough_string)
xml = reparsed.toprettyxml(indent="\t")
return xml
def prettify(response):
if isinstance(response, str) or isinstance(response, bytes):
return prettify_by_str(response, make_pretty_xml)
else:
return prettify_by_response(response, make_pretty_xml)
在 prettify_by_response 和 prettify_by_str 函数中,我将函数 make_pretty_xml 作为参数传递
我可以简单地调用该函数,而不是将函数作为参数传递。例如
def prettify_by_str(xml_str, prettify_func):
root = ET.fromstring(xml_str)
return make_pretty_xml(root)
将函数作为参数传递给这些函数而不是直接调用该函数的优点之一是,该函数与 make_pretty_xml 函数不紧密耦合。
还有什么其他优势或者我是否增加了额外的复杂性?
【问题讨论】:
-
提示,你可以用
isinstance(response, (str,bytes))替换if
标签: python functional-programming higher-order-functions