PEP8格式:带缩进和嵌套括号的长行

时间:2014-10-03 18:03:30

标签: python indentation brackets pep8

作为一名python初学者,我一直在寻找符合PEP8标准的格式化以下代码行的方式(这也使得PyCharm感到高兴)。这是:

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来缩短这条丑陋的线条。你觉得怎么样?

1 个答案:

答案 0 :(得分:3)

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

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