测试开发Python接口自动化测试Python接口测试

简明概述

2017-05-06  本文已影响29人  七月尾巴_葵花

编码

代码格式

缩进

行宽

每行代码尽量不超过80个字符(在特殊情况下可以略微超过80,但最长不得超过120)

理由:

引号

简单说,自然语言使用双引号,机器标示使用单引号,因此 代码里 多数应该使用 单引号

空行

class A:

    def __init__(self):
        pass

    def hello(self):
        pass


def main():
    pass   

编码

import语句

# 正确的写法
import os
import sys

# 不推荐的写法
import sys,os

# 正确的写法
from subprocess import Popen, PIPE
# 正确的写法
from foo.bar import Bar

# 不推荐的写法
from ..bar import Bar
import os
import sys

import msgpack
import zmq

import foo
from myclass import MyClass
import bar
import foo.bar

bar.Bar()
foo.bar.Bar()

空格

# 正确的写法
i = i + 1
submitted += 1
x = x * 2 - 1
hypot2 = x * x + y * y
c = (a + b) * (a - b)

# 不推荐的写法
i=i+1
submitted +=1
x = x*2 - 1
hypot2 = x*x + y*y
c = (a+b) * (a-b)
# 正确的写法
def complex(real, imag):
    pass

# 不推荐的写法
def complex(real,imag):
    pass
# 正确的写法
def complex(real, imag=0.0):
    pass

# 不推荐的写法
def complex(real, imag = 0.0):
    pass
# 正确的写法
spam(ham[1], {eggs: 2})

# 不推荐的写法
spam( ham[1], { eggs : 2 } )
# 正确的写法
dict['key'] = list[index]

# 不推荐的写法
dict ['key'] = list [index]
# 正确的写法
x = 1
y = 2
long_variable = 3

# 不推荐的写法
x             = 1
y             = 2
long_variable = 3

换行

Python支持括号内的换行。这时有两种情况。

  1. 第二行缩进到括号的起始处
foo = long_function_name(var_one, var_two,
                         var_three, var_four)
  1. 第二行缩进4个空格,适用于起始括号就换行的情形
def long_function_name(
        var_one, var_two, var_three,
        var_four):
    print(var_one)

使用反斜杠\换行,二元运算符+ .等应出现在行末;长字符串也可以用此法换行

session.query(MyTable).\
        filter_by(id=1).\
        one()

print 'Hello, '\
      '%s %s!' %\
      ('Harry', 'Potter')

禁止复合语句,即一行中包含多个语句:

# 正确的写法
do_first()
do_second()
do_third()

# 不推荐的写法
do_first();do_second();do_third();

if/for/while一定要换行:

# 正确的写法
if foo == 'blah':
    do_blah_thing()

# 不推荐的写法
if foo == 'blah': do_blash_thing()

注释

块注释

“#”号后空一格,段落件用空行分开(同样需要“#”号)

# 块注释
# 块注释
#
# 块注释
# 块注释

行注释

至少使用两个空格和语句分开,注意不要使用无意义的注释

# 正确的写法
x = x + 1  # 边框加粗一个像素

# 不推荐的写法(无意义的注释)
x = x + 1 # x加1

docstring

重要的两点:

  1. 所有的公共模块、函数、类、方法,都应该写docstring。私有方法不一定需要,但应该在def后提供一个块注释来说明。
  2. docstring的结束"""应该独占一行,除非此docstring只有一行。
"""Return a foobar
Optional plotz says to frobnicate the bizbaz first.
"""

"""Oneline docstring"""

命名规范

MAX_OVERFLOW = 100

Class FooBar:

    def foo_bar(self, print_):
        print(print_)

上一篇 下一篇

猜你喜欢

热点阅读