Python 函数有太多带有默认值的参数,如何使其更简洁?
我有以下函数签名,它看起来真的很难看,我该怎么做才能使它看起来更干净?
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,):
I have the following function signature, and it looks really ugly, what can I do to make it look cleaner ?
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,):
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果我是你,我想我会这样做:
希望这会对你有所帮助。
if i were you i think i will do it like this:
hope this will help you.
我的建议是删除参数。您真的需要能够单独指定所有模板吗?只指定模板文件夹,然后强制其中包含 subject.txt、msg.html 等内容,难道还不够吗?
如果您只是想提高可读性,请将其重新格式化为每行一个参数:
这将使读者更快地掌握参数名称。
My proposal is to drop parameters. Do you really need to be able to specify all the templates separately? Wouldn't it be sufficient to just specify the template folder, and then mandate that it has subject.txt, msg.html, etc in it?
If you just want to improve readability, reformat it to have one parameter per line:
This will allow a reader to more quickly grasp what the parameter names are.
您可以将其重写为:
You could rewrite it as:
话虽如此,我认为您当前的解决方案比使用
**kwargs
更好。With that said, I think your current solution is waaay better than using
**kwargs
.这对我来说似乎并不那么丑陋:你有一个函数,你有足够的参数来修改函数的行为方式,并且你有合理的默认值,这样你就不需要在每个函数调用时指定所有参数。
可以将函数打包在类中:在类构造函数中,您指定参数列表中的所有这些值,并且您有一个不带参数的特殊方法来执行核心功能。
像这样的东西:
(我从参数名称中猜测哪些值是特定于站点的,哪些是特定于用户的。我不知道您的具体应用程序,请按照您想要的方式进行调整)
this does not seem so ugly to me: you have a function, you have enough parameters to modify the way the function behave, and you have sensible default values so that you don't need to specify all arguments at each function call.
there is the possibility to package the function in a class: in the class constructor, you specify all those values which are part of the parameter list, and you have a special method without arguments to execute the core feature.
something like this:
(i guessed which values is site specific and which is user specific from the name of the parameters. i don't know your specific application, adapt it the way you want)