Python代码格式化

Cur*_*arn 4 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)
Run Code Online (Sandbox Code Playgroud)

通过使用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)
Run Code Online (Sandbox Code Playgroud)

unu*_*tbu 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)
Run Code Online (Sandbox Code Playgroud)

要保持视觉上有意义的缩进级别,请使用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))
Run Code Online (Sandbox Code Playgroud)


Dan*_*ach 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))
Run Code Online (Sandbox Code Playgroud)

但是,我会考虑更像这样写:(代码未经测试)

def __str__(self):
    return """\
Car Type 
mpg: %(mpg).1f 
hp: %(hp).2f
pc: %(pc)i 
unit cost: $%(cost).2f 
price: $%(price).2f """ % self.__dict__
Run Code Online (Sandbox Code Playgroud)

  • @Mike强调"我会考虑".如果我正在写`__str__`,我可能知道它们是否相同. (2认同)