gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 01:13:29 25 4
gpt4 key购买 nike

作为 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com