您可以通过使用*args
和**kwargs
给你的函数签名添加任意的论点支持,再传给那些:
def chart_selector(slide, df_table, chart_type, *args, **kwargs):
if chart_type == "bar":
add_bar_chrt(slide, df_table, *args, **kwargs)
任何额外您现在传递给chart_selector()
的论点现在转交给add_bar_chrt()
。
当你在这个函数的工作,无论如何,考虑使用字典派遣图表类型:
chart_types = {
'bar': add_bar_chrt,
'column': add_column_chrt,
'pie': add_pie_chart,
'line': add_line_chart,
}
def chart_selector(slide, df_table, chart_type, *args, **kwargs):
return chart_types[chart_type](slide, df_table, *args, **kwargs)
字典取代多分枝if
.. elif
..结构。
演示:
>>> def add_bar_chrt(slide, tbl, size=10, color='pink'):
... return 'Created a {} barchart, with bars size {}'.format(size, color)
...
>>> def add_column_chrt(slide, tbl, style='corinthyan', material='marble'):
... return 'Created a {} column chart, with {}-style plinths'.format(material, style)
...
>>> chart_types = {
... 'bar': add_bar_chrt,
... 'column': add_column_chrt,
... }
>>> def chart_selector(slide, df_table, chart_type, *args, **kwargs):
... return chart_types[chart_type](slide, df_table, *args, **kwargs)
...
>>> chart_selector('spam', 'eggs', 'bar')
'Created a 10 barchart, with bars size pink'
>>> chart_selector('spam', 'eggs', 'column', material='gold')
'Created a gold column chart, with corinthyan-style plinths'
这实在是不清楚。为什么你不能把它们放在if语句中的add_bar_chrt的调用中? – 2014-10-08 11:21:42
只需将其他参数添加到函数调用中,例如'add_bar_chrt(幻灯片,df_table,optional_arg1,optional_arg2,anotherarg = 123)' – mhawke 2014-10-08 11:22:02
@ Daniel Roseman,道歉,但这个话题本身让我感到困惑,但我相信我已经完成了你的建议? – 2014-10-08 11:24:19