codecamp

Python 缩进规范 4 空格 | Google 官方对齐方式

缩进

Tip

用4个空格作为缩进。

不要使用制表符。使用隐式续行时,应该把括起来的元素垂直对齐(参见 行宽 章节的示例),或者添加4个空格的悬挂缩进。右括号(圆括号,方括号或花括号)可以置于表达式结尾或者另起一行。另起一行时右括号应该和左括号所在的那一行缩进相同。

正确:

## 与左括号对齐。
foo = long_function_name(var_one, var_two,
                         var_three, var_four)
meal = (spam,
        beans)


## 与字典的左括号对齐。
foo = {
    'long_dictionary_key': value1 +
                           value2,
    ...
}


## 4个空格的悬挂缩进;首行没有元素
foo = long_function_name(
    var_one, var_two, var_three,
    var_four)
meal = (
    spam,
    beans)


## 4个空格的悬挂缩进;首行没有元素
## 右括号另起一行。
foo = long_function_name(
    var_one, var_two, var_three,
    var_four
)
meal = (
    spam,
    beans,
)


## 字典中的4空格悬挂缩进。
foo = {
    'long_dictionary_key':
        long_dictionary_value,
    ...
}

错误:

## 首行不能有元素。
foo = long_function_name(var_one, var_two,
    var_three, var_four)


## 禁止2个空格的悬挂缩进。
foo = long_function_name(
  var_one, var_two, var_three,
  var_four)


## 字典没有悬挂缩进。
foo = {
    'long_dictionary_key':
    long_dictionary_value,
    ...
}
Python 括号使用规范 | Google 官方风格指南
Python 尾逗号规范 | Google 官方序列格式
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }