Skip to main content
 首页 » 编程设计

python之我怎样才能使这个代码片段更漂亮

2025年05月04日14lyj

我正在寻找一种方法来缩短这个 python3 函数。该函数需要大量输入变量并检查每个变量以查看它是否为 None。有没有办法遍历所有输入变量并将不是 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) 

请您参考如下方法:

看起来所有参数都被直接传递给 make_cmd 所以为什么不使用关键字参数:

def news(self, **params): 
    self.make_cmd('GET', 'news', params) 
 
news(query="Test")