我发送的ajax请求带有一个包含字符串的“data”字段,以及用户设置的多个选项。每个选项将“启用”或“禁用”,并将用于启用或禁用类中的功能。我想知道的是,是否有更好的方法来组织这个代码,不涉及调用每个函数并检查它是否启用或禁用?
class Parse(webapp2.RequestHandler):
def post(self):
data = self.request.get("data")
func1_option = self.request.get("func1_option")
func2_option = self.request.get("func2_option")
func3_option = self.request.get("func3_option")
newData = func1(func2(func3(data)))
self.response.write(newData)
def func1(foo):
if funct1_option = "disabled":
return foo
else:
return some.function(foo)
def func2(foo):
if funct2_option = "disabled":
return foo
else:
return some.function(foo)
def func3(foo):
if funct3_option = "disabled":
return foo
else:
return some.function(foo)
答案 0 :(得分:1)
class Parse(webapp2.RequestHandler):
def post(self):
data = self.request.get("data")
# Note - order reversed
funcs = [
("func3_option", some.other_other_function),
("func2_option", some.other_function),
("func1_option", some.function)
]
for opt_name, func in funcs:
if self.request.get(opt_name) != "disabled":
data = func(data)
self.response.write(data)