Python函数有太多默认参数,如何简化?

2 投票
5 回答
3598 浏览
提问于 2025-04-16 06:23

我有一个这样的函数签名,看起来非常复杂,我该怎么做才能让它看起来更简洁一些呢?

def contact(
  request, sender=settings.DEFAULT_FROM_EMAIL,
  subj_tmpl='contato/subject.txt',msg_tmpl='contato/msg.html',
  template='contato/contato.html', success_template='contato/success.html',
  success_redir='/',append_message=None,):

5 个回答

0

你可以把它改写成:

def contact( request, **kargs):
    try:
        sender = kwargs.pop ('sender')
    except KeyError:
        sender=settings.DEFAULT_FROM_EMAIL

    try:
        subj_tmpl = kwargs.pop ('subj_tmpl')
    except KeyError:
        subj_tmpl='contato/subject.txt'

    # ... 
    # and so on 
    # ...
3

我的建议是去掉一些参数。你真的需要单独指定所有的模板吗?是不是只需要指定一个模板文件夹,然后要求里面有subject.txt、msg.html等文件就可以了?

如果你只是想提高可读性,可以把每个参数放在单独的一行:

def contact(
  request, 
  sender=settings.DEFAULT_FROM_EMAIL,
  subj_tmpl='contato/subject.txt',
  msg_tmpl='contato/msg.html',
  template='contato/contato.html', 
  success_template='contato/success.html',
  success_redir='/',
  append_message=None,):

这样读的人就能更快地理解每个参数的名字是什么了。

4

如果我是你,我会这样做:

def contact(request, sender=None, append_message=None, context=None):

   if not sender:
       sender = settings.DEFAULT_FROM_EMAIL  # i hope that you can access settings here

   # The context arg is a dictionary where you can put all the others argument and 
   # you can use it like so :

   subj_tmpl = context.get('subj_tmpl', 'contato/subject.txt')
   # ....

希望这能帮到你。

撰写回答