为了回应我的另一个问题,有人建议我避免在代码中使用很长的行,并在编写Python代码时使用PEP-8规则。 PEP-8规则之一建议避免超过80个字符的行。我改变了很多代码以符合这个要求,没有任何问题。但是,按照下面显示的方式更改以下行将破坏代码。任何想法为什么?是否与return
命令后面的内容必须在一行中有关?Python代码格式化
线长于80个字符:
def __str__(self):
return "Car Type \n"+"mpg: %.1f \n" % self.mpg + "hp: %.2f \n" %(self.hp) + "pc: %i \n" %self.pc + "unit cost: $%.2f \n" %(self.cost) + "price: $%.2f "%(self.price)
线通过使用Enter
密钥和Spaces
适当变更:
def __str__(self):
return "Car Type \n"+"mpg: %.1f \n" % self.mpg +
"hp: %.2f \n" %(self.hp) + "pc: %i \n" %self.pc +
"unit cost: $%.2f \n" %(self.cost) + "price: $%.2f "%(self.price)
首先摆脱字符串连接并使用%s替换,这将大大缩短行。像这样的东西。 'Car Type \ nmpg:%.1f \ n%d hp:%.2f \ npc:%i \ nunit cost:$%。2f \ nprice:$%。2f'%(self.mpg,self.hp,self .pc,self.cost,self.price),你甚至可以命名替换,使它更清晰你在做什么。 – 2010-05-08 04:04:00
PEP建议非常差并且过时;将代码压缩到79列是一种很好的方法,因为PEP示例本身可以生动地展现出一些不可读的代码。 120列更合理,迫使更少的行被拆分。 80列屏幕*不是一个严重的开发环境。 – 2010-05-08 16:53:58