2014-10-08 68 views
0

我有一个函数,它具有多个函数,所有这些函数都带有2个必需参数和许多可选参数。我想知道如何在这个函数中设置可选的参数给定函数:Python:为函数中的函数设置参数

chart_type = "bar" 

def chart_selector(slide, df_table, chart_type): 

    if chart_type == "bar": 
     add_bar_chrt(slide, df_table) 
    elif chart_type == "column": 
     add_column_chrt(slide, df_table) 
    elif chart_type == "pie": 
     add_pie_chrt(slide, df_table) 
    elif chart_type == "line": 
     add_line_chrt(slide, df_table) 

这里是我想怎么办:我想使用chart_selector()功能,如果chart_type"bar",然后我想要为add_bar_chrt()函数设置几个可选参数,但我不知道如何?

,所以我需要它以某种方式加入到这个代码:

chart = chart_selector(slide, df_table, chart_type) 
+0

这实在是不清楚。为什么你不能把它们放在if语句中的add_bar_chrt的调用中? – 2014-10-08 11:21:42

+0

只需将其他参数添加到函数调用中,例如'add_bar_chrt(幻灯片,df_table,optional_arg1,optional_arg2,anotherarg = 123)' – mhawke 2014-10-08 11:22:02

+0

@ Daniel Roseman,道歉,但这个话题本身让我感到困惑,但我相信我已经完成了你的建议? – 2014-10-08 11:24:19

回答

2

您可以通过使用*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' 
+0

使用字典替换操作符是一个好主意。现在就尝试所有这些,并让你知道它是怎么回事! – 2014-10-08 11:27:26

+0

非常感谢您的时间和精力,它运作良好!现在我知道* args和** kwargs会做什么,并会在未来尝试使用它们。 – 2014-10-08 11:48:21