Python代码格式化

时间:2010-05-08 03:58:35

标签: 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 个答案:

答案 0 :(得分: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))

答案 1 :(得分: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__

答案 2 :(得分: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本身会导致语法错误。

答案 3 :(得分:3)

它需要一些额外的设置,但数据驱动的方法(具有良好的垂直对齐剂量)很容易随着项目的发展而变化和修改。它间接消除了长行代码的问题。

def __str__(self):
    dd = (
        ("Car Type     %s",    ''),
        ("  mpg:       %.1f",  self.mpg),
        ("  hp:        %.2f",  self.hp),
        ("  pc:        %i",    self.pc),
        ("  unit cost: $%.2f", self.cost),
        ("  price:     $%.2f", self.price),
    )

    fmt = ''.join("%s\n" % t[0] for t in dd)
    return fmt % tuple(t[1] for t in dd)
相关问题