如何在Python中使用三元运算符

时间:2013-01-14 17:52:22

标签: python

我有这个方法:

def get_compression_settings(self, media_type=None):
        return self.transmit('GET', 'compression?mediatypeid={0}'.format(media_type))

有没有办法可以检查media_type == None,只有在使用三元运算符的单行中〜= None时才附加mediatypeid = {0}?

我知道我可以做到以下几点,但如果我的方法可以只是一次返​​回就更好了:

def get_compression_settings(self, media_type=None):
        endpoint = 'compression?mediatypeid={0}'.format(media_type) if media_type is not None else 'compression'
        return self.transmit('GET', endpoint)

2 个答案:

答案 0 :(得分:3)

它可以是单行返回,如:

return self.transmit('GET', 'compression?mediatypeid={0}'.format(media_type)
                             if media_type is not None else 'compression')

我将它分成多行以提高可读性,但这不是必须的。 (请注意,这需要将示例中的if media_type not none更改为if media_type is not None)。

答案 1 :(得分:1)

你试过这个吗?

return self.transmit('GET', 'compression?mediatypeid={0}'.format(media_type) if media_type is not None else 'compression')