Python 代码格式化
在我之前的一个问题中,有人建议我在写Python代码时避免写太长的代码行,并遵循PEP-8的规则。PEP-8的一个规则是建议代码行不要超过80个字符。我把很多代码都改成了符合这个要求,没遇到什么问题。不过,下面这行代码我按照建议的方式修改后却出现了问题。有人知道为什么吗?这是不是因为return
后面的内容必须写在同一行呢?
超过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)
4 个回答
6
你可以通过把这个表达式放在括号里来解决这个问题:
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))
不过,我觉得可以这样写会更好一点:(这个代码还没测试过)
def __str__(self):
return """\
Car Type
mpg: %(mpg).1f
hp: %(hp).2f
pc: %(pc)i
unit cost: $%(cost).2f
price: $%(price).2f """ % self.__dict__
13
多行字符串会更容易阅读:
def __str__(self):
return '''\
Car Type
mpg: %.1f
hp: %.2f
pc: %i
unit cost: $%.2f
price: $%.2f'''% (self.mpg,self.hp,self.pc,self.cost,self.price)
为了保持视觉上有意义的缩进层级,可以使用 textwrap.dedent
:
import textwrap
def __str__(self):
return textwrap.dedent('''\
Car Type
mpg: %.1f
hp: %.2f
pc: %i
unit cost: $%.2f
price: $%.2f'''% (self.mpg,self.hp,self.pc,self.cost,self.price))
4
在Python中,你不能在表达式中随便换行;最简单的解决办法是在行末加一个反斜杠。
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)
在这种情况下,反斜杠必须是这一行的最后一个字符。它的意思就是“忽略这里的换行”。换句话说,你是在“逃避”这个换行,因为通常换行是一个重要的分隔符。
你可以随时用反斜杠来“逃避”一个本来重要的换行。虽然这样做有点傻,但你甚至可以这样做
def foo():
return \
1
这样的话,foo()
就会返回1。如果没有反斜杠,单独的1就会导致语法错误。