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年)建议使用括号。

  • 相关阅读:
    php的多态性
    php接口
    php抽象类和抽象方法
    php类与对象的魔术方法
    php关键字
    php类型之class类,对象,构造函数的理解
    php日期格式化
    php之常用字符串方法
    php将获取的数组变成字符串传入txt文本。。。
    PHP之键值操作函数
  • 原文地址:https://www.cnblogs.com/hokky/p/8566121.html
Copyright © 2011-2022 走看看