我有如下代码:
if text == 'today':
date1, date2 = dt.today_()
result, data = ga.get_sessions_today_data(user_id, date1, date2)
result, data, caption = get_final_caption(result, data, date1, date2, 'hour', 'sessions')
handle_result(chat_id, result, data, caption)
elif text == 'yesterday':
date1, date2 = dt.yesterday()
result, data = ga.get_sessions_today_data(user_id, date1, date2)
result, data, caption = get_final_caption(result, data, date1, end_date, 'hour', 'sessions')
handle_result(chat_id, result, data, caption)
...
Run Code Online (Sandbox Code Playgroud)
代码重复了很多次,只是dt.function()和ga.function()不同.我怎样才能优化代码?
你可以制作一个包含各种可能性函数的字典text.不要在函数后面添加括号,因为你不想调用它们:
options = {"today": dt.today_, "yesterday": dt.yesterday} # etc
Run Code Online (Sandbox Code Playgroud)
然后,您可以执行此操作来替换现有代码:
date1, date2 = options[text]() # Get the correct function and call it
result, data = ga.get_sessions_today_data(user_id, date1, date2)
result, data, caption = get_final_caption(result, data, date1, date2, 'hour', 'sessions')
handle_result(chat_id, result, data, caption)
Run Code Online (Sandbox Code Playgroud)