如何在不使Python代码难看的情况下将其保持在80个字符以下?

2024-06-01 07:15:31 发布

您现在位置:Python中文网/ 问答频道 /正文

这个问题在我的所有编程、python和其他程序中一直重复出现。如果可能的话,我真的很喜欢把代码控制在80个字符以下。在Perl这样的语言中,这并不难,因为空白并不重要。在Python中,当它出现的时候,我常常会把头撞在墙上,而不是想用一种“好”的方式来分割我的长线。那么,代码大师,你是怎么做到的?你能告诉我什么总体策略吗?

我现在要处理的一个特殊问题是:

self.SomeLongLongName = SomeLongLongName.SomeLongLongName(some_obj, self.user1, self.user2)

当我自然而然地尝试用Python来切断这个连接时,我能找到的唯一半正派的方法似乎是:

self.SomeLongLongName = SomeLongLongName.SomeLongLongName(some_obj,
                                                          self.user1
                                                          self.user2)

看起来没那么糟,我想,但它占了三行,这是完全没有必要的。一定有更好的办法,不是吗?

注:我知道你们中有些人不喜欢一行80个字符,并创造了自己的极限。我理解这背后的动机并尊重它,但80个字符是我的首选限制。请不要占用空间试图说服我去120或一些这样的地方。


Tags: 代码self程序语言obj编程方式some
1条回答
网友
1楼 · 发布于 2024-06-01 07:15:31

The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation. Make sure to indent the continued line appropriately. The preferred place to break around a binary operator is after the operator, not before it.

PEP 8 Style Guide for Python Code(按链接查看示例)。

相关问题 更多 >