Python中三元运算符的使用

2024-10-01 17:29:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个方法:

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

有没有一种方法可以使用三元运算符在一行中检查media\u type==None和append mediatypeid={0}如果是~=None?你知道吗

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

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)

Tags: 方法selfnoneformatgetreturnsettingsdef
2条回答

你试过这个吗?你知道吗

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

它可以是单行返回,如下所示:

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)。你知道吗

相关问题 更多 >

    热门问题