zoukankan      html  css  js  c++  java
  • 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年)建议使用括号。

  • 相关阅读:
    js实现将字符串里包含手机号的中间四位替换为****
    草稿for套for
    js实现将时间戳转换成2017-05-06 09:03:02
    时间日期校验接口
    JS延迟导航nav
    nav导航
    鼠标滚动请求加载
    常用开源Jabber(XMPP) IM服务器介绍(转)
    01.base-v1.js
    Haproxy安装及配置(转)
  • 原文地址:https://www.cnblogs.com/hokky/p/8566121.html
Copyright © 2011-2022 走看看