python - PEP8 格式化 : long line with indentation and nested brackets

标签 python indentation brackets pep8

作为一名 Python 初学者,我一直在寻找一种符合 PEP8 的方式来格式化以下代码行(这也让 PyC​​harm 感到高兴)。这是:

print("{}! The {} {} ".format(self.monster.battlecry(),
                              self.monster.color,
                              self.monster.__class__.__name__)
      + self.monster_deaths.pop(self.monster_deaths.index(random.choice(self.monster_deaths))))

我特别担心最后一行有 4 个括号。另外,我应该像往常一样将最后一行缩进 4 个空格,还是再缩进一点以将其与 print 的内容对齐?

以下内容更合适吗?

print("{}! The {} {} ".format(self.monster.battlecry(),
                              self.monster.color,
                              self.monster.__class__.__name__)
       + self.monster_deaths.pop(
             self.monster_deaths.index(
                 random.choice(self.monster_deaths)
                 )
             )
      )

另一种方法是通过创建变量d = self.monster_deaths来缩短这条丑陋的线。你觉得怎么样?

最佳答案

使用临时变量缩短行的替代方法是正确的方法。在这种情况下,您还可以将其添加到格式语句中,而不是使用字符串连接:

d = self.monster_deaths.pop(...)
print("{}! The {} {} {}".format(self.monster.battlecry(),
                                self.monster.color,
                                type(self.monster).name,
                                d))

关于python - PEP8 格式化 : long line with indentation and nested brackets,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26184280/

相关文章:

c# - 缩进多行文本

syntax - Fortran 传递带括号的参数可防止更改

c - pow() 函数在括号中使用时出现奇怪的行为并且带有 long long integer

c++ - C++ 中的大括号语法和迭代器

python - 如何在 Anaconda 中安装 Kivy?

python - AWS Sagemaker Studio,无法加载pickle文件

intellij-idea - 在IntelliJ IDEA中更改选项卡->空间->选项卡的快捷方式

python - 过滤元组列表以删除所有奇数或总和小于 80 的列表

python - 如何向 PyPi 分发类型提示?

javascript - IntelliJ - Javascript 中的制表符缩进不起作用