【问题标题】:How to properly format long lines in Python?如何在 Python 中正确格式化长行?
【发布时间】:2016-09-12 22:17:27
【问题描述】:

我相信我们都熟悉PEP 8,以及它的行长规范。不幸的是,数学是存在的。

我正在尝试用 Python 编写非常长的方程式(三角函数、复杂形状的表面积等),并且我希望能够在我的公式中保持清晰,而不会过多地破坏我的线条。

例如,这个公式很长,在我的代码中可能会缩进很多次,留给我的工作空间不大:

    slantHeight = ((math.sqrt(((baseSideLength/2) * (baseSideLength/2)) + heightSquared))

推荐的打破这条线的方法是什么?

【问题讨论】:

  • 你能解释一下你的用例是什么吗?也许还有另一种技术可以得到你想要的。
  • 你到底想标记什么?
  • 你的意思是一次性变量名like _
  • 不改变语言和解释器。

标签: python code-organization


【解决方案1】:

你可以这样做:

slantHeight = math.sqrt(
    (  # halfBaseSideLengthSquared
        (  # halfBaseSideLength
            baseSideLength / 2) *
        (baseSideLength / 2)) +
    (  # heightSquared
        height * height))

或者这个:

def _(name, x):
    return x

slantHeight = math.sqrt(_('halfBaseSideLengthSquared', _('halfBaseSideLength', baseSideLength / 2) * (baseSideLength / 2)) + _('heightSquared', height * height))

您甚至可以删除 name 参数,因为它被忽略了,但我看不出这有什么帮助。

我建议您不要过多担心文件大小,而是关注可读性。额外的线条不会受到伤害。像这样的:

halfBaseSideLength = (.5 * baseSideLength)
halfBaseSideLengthSquared = (halfBaseSideLength * halfBaseSideLength)

很有用,因为它减少了重复,尽管更好的做法是:

halfBaseSideLengthSquared = (.5 * baseSideLength) ** 2

【讨论】:

  • 然而多年后,我在查看了与它相关的可怕源代码后回到了这个问题。事实证明,我只需要编写更具可读性的代码!想象一下。
猜你喜欢
  • 2020-02-22
  • 1970-01-01
  • 2014-09-22
  • 2011-10-01
  • 2011-02-07
  • 1970-01-01
  • 2012-06-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多