【发布时间】:2018-07-14 13:02:13
【问题描述】:
我正在寻找一种方法来缩短这个 python3 函数。该函数需要大量输入变量并检查每个变量以查看它是否为无。有没有办法遍历所有输入变量并将不是 None 的变量添加到 params 字典中?
def news(self, query = None, instrument_id = None, days = None, news_lang = None, news_country = None, market_id = None, limit = None, offset = None, source_id = None):
params = {}
if query is not None:
params['query'] = query
if instrument_id is not None:
params['instrument_id'] = instrument_id
if news_lang is not None:
params['news_lang'] = news_lang
if news_country is not None:
params['news_country'] = news_country
if limit is not None:
params['limit'] = limit
if offset is not None:
params['offset'] = offset
if source_id is not None:
params['source_id'] = source_id
self.make_cmd('GET', 'news', params)
【问题讨论】:
-
你为什么不用
*args? -
你应该退后一步,问问自己为什么函数需要这么多参数。
-
这看起来应该是某个 other 类的
__init__方法。 (单看名字,我也怀疑make_cmd。) -
@mkrieger1,我绝对同意你的看法。看来这个方法,因为他使用
self作为第一个参数,所以参数太多了,这显然是一个代码问题。
标签: python python-3.x loops