2013-01-14 20 views
-1

我有這樣的方法:如何使用三元運算符在Python

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

有沒有一種方法可以檢查是否MEDIA_TYPE ==無,只追加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) 
+3

你可以有一個單行方法體,但我認爲你應該更喜歡一個可讀的方法。 –

+0

爲什麼這個問題會被降低? – doremi

回答

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)。

+0

我修正了none問題。謝謝! – doremi

+0

這是否回答你的問題關於它在一條線上? –

1

你試過嗎?

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

這將保持'if media_type not none'的語法錯誤 –

+0

@DavidRobinson感謝您的領導...... – ATOzTOA

+0

也不要忘記將'none'改爲'None'(然後我會很樂意刪除我的downvote) –