首页 > 解决方案 > pep 是鼓励还是不鼓励链式方法(方法级联)?

问题描述

受这篇文章的启发,我假设 PEP8 不鼓励链式方法(方法级联)。

内置插件就是证明。

>>> x = list()
>>> x.append(1).append(2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'append'

但我没有通过搜索pep找到相关文档

任何想法?

标签: pythonpep

解决方案


PEP 8 让您决定如何最好地布局您的代码。贯穿始终的关键主题是您的代码应该清晰易读。您提供的示例不起作用,因为 .append 不返回任何内容。

这是一个带有字符串的示例:

x = "This"
x = x.strip().replace("T","t")
print (x)

在以下布局中可能更容易阅读:

x = "This"
x = (x
     .strip()
     .replace("T","t")
     )
print (x)

推荐阅读