Python代码风格指南:pep8

本文详细介绍了代码布局的标准,包括缩进规则、括号内的垂直隐式缩进和悬挂缩进的应用等。并给出了if语句跨行时的不同写法示例及推荐格式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

代码布局

  • 缩进

每级缩进用4个空格。
括号中使用垂直隐式缩进或使用悬挂缩进。后者应注意第一行要没有参数,后续行要有缩进。

  • Yes
# 对准左括号
foo = long_function_name(var_one, var_two,
                         var_three, var_four)

# 不对准左括号,但加多一层缩进,以和后面内容区别。
def long_function_name(
        var_one, var_two, var_three,
        var_four):
    print(var_one)

# 悬挂缩进必须加多一层缩进.
foo = long_function_name(
    var_one, var_two,
    var_three, var_four)
  • No
# 不使用垂直对齐时,第一行不能有参数。
foo = long_function_name(var_one, var_two,
    var_three, var_four)

# 参数的缩进和后续内容缩进不能区别。
def long_function_name(
    var_one, var_two, var_three,
    var_four):
    print(var_one)

四个空格的规则是对续行可选的。

# 悬挂缩进不一定是4个空格
foo = long_function_name(
  var_one, var_two,
  var_three, var_four)

if语句跨行时,两个字符关键字(比如if)加上一个空格,再加上左括号构成了很好的缩进。后续行暂时没有规定,至少有如下三种格式,建议使用第三种。

# 没有额外缩进,不是很好看,个人不推荐.
if (this_is_one_thing and
    that_is_another_thing):
    do_something()

# 添加注释
if (this_is_one_thing and
    that_is_another_thing):
    # Since both conditions are true, we can frobnicate.
    do_something()

# 额外添加缩进,推荐。
# Add some extra indentation on the conditional continuation line.
if (this_is_one_thing
        and that_is_another_thing):
    do_something()

右边括号也可以另起一行。有两种格式,建议第2种。

# 右括号不回退,个人不推荐
my_list = [
    1, 2, 3,
    4, 5, 6,
    ]
result = some_function_that_takes_arguments(
    'a', 'b', 'c',
    'd', 'e', 'f',
    )

# 右括号回退
my_list = [
    1, 2, 3,
    4, 5, 6,
]
result = some_function_that_takes_arguments(
    'a', 'b', 'c',
    'd', 'e', 'f',
)

未完待续……
参考链接:开源中国https://my.oschina.net/u/1433482/blog/464444

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值