Python PEP8格式:带缩进和嵌套括号的长线
作为一名python初学者,我一直在寻找一种符合PEP8的方式来格式化以下代码行(这也让PyCharm感到高兴)。这是:Python PEP8格式:带缩进和嵌套括号的长线,python,indentation,brackets,pep8,Python,Indentation,Brackets,Pep8,作为一名python初学者,我一直在寻找一种符合PEP8的方式来格式化以下代码行(这也让PyCharm感到高兴)。这是: print("{}! The {} {} ".format(self.monster.battlecry(), self.monster.color, self.monster.__class__.__name__) + self.monster
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("{}! 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\u deations
来缩短这条丑陋的线。你认为呢?用临时变量缩短行是正确的方法。在这种情况下,也可以将其添加到format语句中,而不是使用字符串连接:
d = self.monster_deaths.pop(...)
print("{}! The {} {} {}".format(self.monster.battlecry(),
self.monster.color,
type(self.monster).name,
d))
+1对于临时变量,也更易于通读,并注意到我们正在从列表中弹出一些内容。