Dynamic Keyword Arguments in Python?

前端 未结 4 1819
灰色年华
灰色年华 2020-12-01 10:24

Does python have the ability to create dynamic keywords?

For example:

qset.filter(min_price__usd__range=(min_price, max_price))

I w

4条回答
  •  不思量自难忘°
    2020-12-01 10:39

    Yes, sort of. In your filter method you can declare a wildcard variable that collects all the unknown keyword arguments. Your method might look like this:

    def filter(self, **kwargs):
        for key,value in kwargs:
            if key.startswith('min_price__') and key.endswith('__range'):
                currency = key.replace('min_price__', '').replace('__range','')
                rate = self.current_conversion_rates[currency]
                self.setCurrencyRange(value[0]*rate, value[1]*rate)
    

提交回复
热议问题