Python編碼規范:IF中的多行條件


Python編碼規范:IF中的多行條件

轉載 2017年03月08日 09:40:45

http://blog.csdn.net/wsc449/article/details/60866700

有時我將IF中的長條件分解成幾行。最明顯的方法是:

  if (cond1 == 'val1' and cond2 == 'val2' and
      cond3 == 'val3' and cond4 == 'val4'):
      do_something

 

在視覺上不是非常非常有吸引力,因為動作與條件混合。但是,這是使用正確的Python縮進4個空格的自然方式。

目前我使用:

  if (    cond1 == 'val1' and cond2 == 'val2' and
          cond3 == 'val3' and cond4 == 'val4'):
      do_something

 

但這不是很漂亮。  

 

能推薦一種替代方法嗎?

 

您不需要在第二個條件行上使用4個空格。也許使用:

if (cond1 == 'val1' and cond2 == 'val2' and 
       cond3 == 'val3' and cond4 == 'val4'):
    do_something

 

另外,不要忘記空格比你想象的更靈活:

if (   
       cond1 == 'val1' and cond2 == 'val2' and 
       cond3 == 'val3' and cond4 == 'val4'
   ):
    do_something
if    (cond1 == 'val1' and cond2 == 'val2' and 
       cond3 == 'val3' and cond4 == 'val4'):
    do_something

 

這兩個都是相當丑陋的。

也許失去括號(Style Guide不鼓勵這一點)?

if cond1 == 'val1' and cond2 == 'val2' and \
   cond3 == 'val3' and cond4 == 'val4':
    do_something

 

這至少給你一些區別。

甚至:

if cond1 == 'val1' and cond2 == 'val2' and \
                       cond3 == 'val3' and \
                       cond4 == 'val4':
    do_something

 

我想我更喜歡:

if cond1 == 'val1' and \
   cond2 == 'val2' and \
   cond3 == 'val3' and \
   cond4 == 'val4':
    do_something

 

這里是Style Guide,這(自2010年)建議使用括號。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM