PEP8 Python 编码规范

https://www.python.org/dev/peps/pep-0008/

  • 代码编排
    • 缩进。4个空格的缩进(编辑器都可以完成此功能),不使用Tap,更不能混合使用Tap和空格。
    • 每行最大长度79,换行可以使用反斜杠,最好使用圆括号。换行点要在操作符的后边敲回车。
    • 类和top-level函数定义之间空两行;类中的方法定义之间空一行;函数内逻辑无关段落之间空一行;其他地方尽量不要再空行。
  • 文档编排
    • 不要在一句import中多个库,比如import os, sys不推荐。
  • 空格的使用
    • 操作符左右各加一个空格,不要为了对齐增加空格。
    • 不要将多句语句写在同一行,尽管使用‘;’允许。
  • 文档描述
    • 为所有的共有模块、函数、类、方法写docstrings;非共有的没有必要,但是可以写注释(在def的下一行)。
  • 命名规范
    • 模块命名尽量短小,使用全部小写的方式,可以使用下划线。
    • 包命名尽量短小,使用全部小写的方式,不可以使用下划线。
    • 函数命名使用全部小写的方式,可以使用下划线。
    • 常量命名使用全部大写的方式,可以使用下划线。
    • 类的方法第一个参数必须是self,而静态方法第一个参数必须是cls。
  • 编码建议
    • 尽可能使用‘is’‘is not’取代‘==’,比如if x is not None 要优于if x。
    • 二进制数据判断使用 if boolvalue的方式。

Python 3

  • print('hello')
  • def func(x:str) -> bool
  • 模块改名

核心对象

字符串定义


In [1]:
s = 'hello world'
print s
s = "helloworld"
print s


hello world
helloworld

In [2]:
s = """helloworld
another helloworld"""; 
print s


helloworld
another helloworld

字符串转义字符


In [3]:
s = ""cat""


  File "<ipython-input-3-cb83231f6e1f>", line 1
    s = ""cat""
            ^
SyntaxError: invalid syntax

In [4]:
s = "\"cat\""; print s


"cat"

In [5]:
s = ''cat''


  File "<ipython-input-5-97b472b74729>", line 1
    s = ''cat''
            ^
SyntaxError: invalid syntax

In [6]:
s = '\'cat\''; print s


'cat'

In [7]:
s = '\t\tcat'; print s


		cat

In [8]:
s = 'cat\b'; print s


cat

In [10]:
# 80 char per line
s = 'cat catch \
mouse'
print s


cat catch mouse

In [11]:
s = 'cat catch\nmouse'
print s


cat catch
mouse

字符串格式化


In [ ]:
# %[(name)][flags][width].[precision]typecode

In [12]:
s = "love"
t = "python"

In [13]:
print s + t


lovepython

In [14]:
print s + " " + t


love python

In [15]:
sp = "%s %s" % (s, t); print sp


love python

In [16]:
sp = "%-10s %s" % (s, t); print sp


love       python

In [17]:
sp = "%+10s %s" % (s, t); print sp


      love python

In [18]:
n = 10
print s + " " + n


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-18-18eaf01a9c72> in <module>()
      1 n = 10
----> 2 print s + " " + n

TypeError: cannot concatenate 'str' and 'int' objects

In [22]:
sp = "%s %d" % (s, n)
#int
print sp


love 10

In [23]:
# 转义字符 %
sp = '%%%s%%' % s; print sp


%love%

In [25]:
# 浮点数
pi = 3.1415
sp = '%.2f' % pi;
print sp


3.14

In [26]:
sp = '%.6f' % pi;
print sp


3.141500

In [27]:
# 复杂的case
sp = 'spend $%.02f to buy %d %s' % (1.25, 8, 'cars')
print sp


spend $1.25 to buy 8 cars

In [28]:
# 另外一种写法
sp = 'spend ${0} to buy {1} {2}'.format(1.25, 8, 'cars')
print sp


spend $1.25 to buy 8 cars

字符串操作


In [ ]:
print s*3

索引和分片


In [ ]:
print s[1:2]

In [ ]:
print s[1:4]

In [ ]:
print s[1:]

In [ ]:
print len(s)

In [ ]:
s = '    car,Bat     '
print s.strip()
print s.rstrip()
print s.lstrip()

In [ ]:
s.replace('a', 'h')

In [ ]:
s.split(',')

In [ ]:
s.upper()

In [ ]:
s.lower()

In [ ]:
s = 'car'
print s.find('a')
print s.find('h')

RAW 字符串


In [ ]:
s = r'\n\n\n\t\"car'
print s

Unicode


In [29]:
s = u'中国'
t = '中国'

In [30]:
print type(s), type(t)


<type 'unicode'> <type 'str'>

In [31]:
s1 = s.encode('utf8')
print type(s1)


<type 'str'>

In [32]:
t1 = t.decode('utf8')
print type(t1)


<type 'unicode'>

In [ ]:
# chardet 库
# codecs

In [33]:
print s, t
print len(s), len(t)


中国 中国
2 6

In [ ]:
import sys
sys.getdefaultencoding()

In [ ]:
# reload(sys)
# print sys.getdefaultencoding()
# sys.setdefaultencoding('utf-8')

In [34]:
x = '\u4e2d\u56fd'
print x


\u4e2d\u56fd

In [35]:
print x.decode('unicode-escape')


中国

数值类型


In [36]:
print 1234, -100, 0, 99999999999999999999999999999999999999999999999999999999999999


1234 -100 0 99999999999999999999999999999999999999999999999999999999999999

In [37]:
99999999999999999999999999999999999999999999999999999999999999 + 1


Out[37]:
100000000000000000000000000000000000000000000000000000000000000L

In [38]:
import sys
print sys.maxint


9223372036854775807

不同进制


In [39]:
print 0777, 0x8ee, 0b100


511 2286 4

In [40]:
print 0xFFFFF100


4294963456

In [41]:
print hex(100), oct(100), bin(100)


0x64 0144 0b1100100

In [42]:
print 1.23, .23, 3.14e-10


1.23 0.23 3.14e-10

In [43]:
print 10e2


1000.0

In [44]:
# 复数
print 3+2j, complex(3, 2)


(3+2j) (3+2j)

类型转换


In [45]:
int(1.23)


Out[45]:
1

In [46]:
float(1)


Out[46]:
1.0

数学操作


In [47]:
print pow(2,3)


8

In [48]:
print abs(-2)


2

In [49]:
print round(2.3)


2.0

In [50]:
print round(2.7)


3.0

列表


In [51]:
# 定义
a = []

In [52]:
a = list(); print a


[]

In [53]:
a = [1, 2, 3]; print a


[1, 2, 3]

In [54]:
a = [1, 2.0, 'str']; print a


[1, 2.0, 'str']

列表操作


In [55]:
len(a)


Out[55]:
3

In [56]:
x = [1, 2, 3] + [8, 'no', 1.0, 2+3j, 2e3]; print x


[1, 2, 3, 8, 'no', 1.0, (2+3j), 2000.0]

In [57]:
x = [1, 2, 3] + 'a'


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-57-e815650eee5d> in <module>()
----> 1 x = [1, 2, 3] + 'a'

TypeError: can only concatenate list (not "str") to list

In [58]:
x = [1, 2] * 4; print x


[1, 2, 1, 2, 1, 2, 1, 2]

In [ ]:
### 分片与索引

In [59]:
a = [1 ,2, 3]
a[0]


Out[59]:
1

In [60]:
a[-1]


Out[60]:
3

In [61]:
a[4]


---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-61-54d383a36828> in <module>()
----> 1 a[4]

IndexError: list index out of range

In [62]:
a[1:]


Out[62]:
[2, 3]

In [63]:
a[2:]


Out[63]:
[3]

In [64]:
a[4:]


Out[64]:
[]

In [65]:
a[1:2]   # 返回的列表 非 元素


Out[65]:
[2]

In [66]:
a[:-1]


Out[66]:
[1, 2]

In [67]:
a[:-2]


Out[67]:
[1]

In [68]:
print a[1:-1]


[2]

In [ ]:
# 修改

In [69]:
a = [1, 2, 3]
a[2] = 4
a


Out[69]:
[1, 2, 4]

In [70]:
a[0] = 5
a


Out[70]:
[5, 2, 4]

操作


In [71]:
a = [1, 2, 3]
print a.append(4) # 为什么这里没有输出?


None

In [72]:
print a


[1, 2, 3, 4]

In [73]:
a.pop(0); print a


[2, 3, 4]

In [74]:
a.pop(-1); print a


[2, 3]

In [75]:
a.insert(0, 1); print a


[1, 2, 3]

In [76]:
a.insert(-1, 4); print a


[1, 2, 4, 3]

In [77]:
a.insert(1, 1.5); print a


[1, 1.5, 2, 4, 3]

In [78]:
a.remove(1.5); print a


[1, 2, 4, 3]

In [79]:
a.remove(8);


---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-79-3eb3d8550517> in <module>()
----> 1 a.remove(8);

ValueError: list.remove(x): x not in list

In [80]:
# 排序
a.sort(); print a


[1, 2, 3, 4]

In [81]:
sorted(a)


Out[81]:
[1, 2, 3, 4]

In [82]:
b = ['cde','abc','ABD', 'acd']
b.sort()
b


Out[82]:
['ABD', 'abc', 'acd', 'cde']

In [ ]:
b.sort(key=str.lower)
b

In [ ]:
b.sort(reverse=True)
b

In [83]:
a = [1,2,3]
a.reverse()
a


Out[83]:
[3, 2, 1]

In [ ]:
# 列表的扩展

In [85]:
a = [1, 23]
b = [2, 89]

In [86]:
a.extend(b)
a


Out[86]:
[1, 23, 2, 89]

In [ ]:
# 索引

In [87]:
a = [3,8,10]
a.index(8)


Out[87]:
1

In [88]:
a.index(10)


Out[88]:
2

In [89]:
a.index(-1)


---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-89-72ca085da67a> in <module>()
----> 1 a.index(-1)

ValueError: -1 is not in list

In [90]:
a = [1, 2, 3]
del a[0]
a


Out[90]:
[2, 3]

In [91]:
del a[-1]
a


Out[91]:
[2]

In [92]:
del a[0]
a


Out[92]:
[]

In [ ]:
# 列表的迭代

In [93]:
a = [1,2,3]
for e in a:
    print e,


1 2 3

字典


In [109]:
d = {}
d


Out[109]:
{}

In [110]:
d = dict()
d


Out[110]:
{}

In [111]:
d = {1:'beijing', 2:'hangzhou'}
d


Out[111]:
{1: 'beijing', 2: 'hangzhou'}

In [112]:
d.keys()


Out[112]:
[1, 2]

In [113]:
d.values()


Out[113]:
['beijing', 'hangzhou']

In [114]:
d.items()


Out[114]:
[(1, 'beijing'), (2, 'hangzhou')]

In [ ]:
# 索引

In [115]:
d[1]


Out[115]:
'beijing'

In [116]:
d[2]


Out[116]:
'hangzhou'

In [117]:
d[3]


---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-117-d787ddb7dc0e> in <module>()
----> 1 d[3]

KeyError: 3

In [118]:
d.has_key(3)


Out[118]:
False

In [ ]:
# 修改

In [119]:
d[1] = 'hebei'
d


Out[119]:
{1: 'hebei', 2: 'hangzhou'}

In [120]:
d.pop(1)
d


Out[120]:
{2: 'hangzhou'}

In [121]:
d.pop(2)
d


Out[121]:
{}

In [122]:
d = {1:'beijing', 2:'hangzhou'}
del d[1]
d


Out[122]:
{2: 'hangzhou'}

In [123]:
d.sort()


---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-123-e2dd2b0a8643> in <module>()
----> 1 d.sort()

AttributeError: 'dict' object has no attribute 'sort'

In [124]:
x = d.keys().sort()
x

In [125]:
d.reverse()


---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-125-1bdee7aaa7ed> in <module>()
----> 1 d.reverse()

AttributeError: 'dict' object has no attribute 'reverse'

集合


In [ ]:
a = set()
a

In [ ]:
a = set([1,2,3])
a

In [ ]:
a = set([1,1])
a

In [ ]:
a = set([1,2,3])
b = set([2,3,4])
a.union(b)

In [ ]:
a = set([1,2,3])
b = set([2,3,4])
a.intersection(b)

In [ ]:
a = set([1,2,3])
b = set([2,3,4])
a.difference(b)

In [ ]:
a = set([1,2,3])
a.add(4)
a

In [ ]:
a = set([1,2,3])
a.add(3)
a

In [ ]:
a = set([1,2,3])
a.clear()
a

In [ ]:
a = set([1,2,3])
a.pop()
a

元组


In [94]:
a = ()
a


Out[94]:
()

In [95]:
a = tuple([1,2])
a


Out[95]:
(1, 2)

In [96]:
a = (2,3,2)
a


Out[96]:
(2, 3, 2)

In [97]:
a = (40)
a


Out[97]:
40

In [98]:
a = (40,)
a


Out[98]:
(40,)

In [99]:
a = (1,2,3,4)
a[0:3]


Out[99]:
(1, 2, 3)

In [100]:
a.remove(2)


---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-100-9481fd5ef2c6> in <module>()
----> 1 a.remove(2)

AttributeError: 'tuple' object has no attribute 'remove'

In [101]:
a.count(2)


Out[101]:
1

In [102]:
a.index(2)


Out[102]:
1

In [103]:
a = (2,3,2)
b = (3,4,5)

In [104]:
a + b


Out[104]:
(2, 3, 2, 3, 4, 5)

In [105]:
a


Out[105]:
(2, 3, 2)

In [106]:
b


Out[106]:
(3, 4, 5)

unpack


In [107]:
(a, b, c) = [1,2,3]
print a, b, c


1 2 3

In [108]:
(a, b) = [1,2,3]
print a, b


---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-108-0865ce155b99> in <module>()
----> 1 (a, b) = [1,2,3]
      2 print a, b

ValueError: too many values to unpack

加减乘除运算


In [126]:
0.2 + 0.1 + 0.3


Out[126]:
0.6000000000000001

In [127]:
1 - 0.9


Out[127]:
0.09999999999999998

In [128]:
import decimal

In [129]:
decimal.Decimal(1) - decimal.Decimal(0.9)


Out[129]:
Decimal('0.09999999999999997779553950750')

In [130]:
decimal.getcontext().prec = 4

In [131]:
decimal.Decimal(1) - decimal.Decimal(0.9)


Out[131]:
Decimal('0.1000')

其他运算


In [132]:
3 ** 3


Out[132]:
27

In [133]:
15//2


Out[133]:
7

In [134]:
15/2


Out[134]:
7

In [135]:
15./2


Out[135]:
7.5

In [136]:
3<2<5


Out[136]:
False

In [137]:
2==2==2


Out[137]:
True

In [138]:
2==2==3


Out[138]:
False

逻辑运算


In [139]:
True and False


Out[139]:
False

In [140]:
True or False


Out[140]:
True

In [141]:
not True


Out[141]:
False

In [142]:
not False


Out[142]:
True

In [143]:
def check():
    print 'done'
    return False
True and check()


done
Out[143]:
False

In [144]:
True or check()


Out[144]:
True

In [145]:
not True and False or True


Out[145]:
True

In [ ]:
not True and False or False

In [146]:
((not True) and False) or True


Out[146]:
True

In [ ]:
((not True) and False) or False

In [147]:
0b11110000 & 0b00001111


Out[147]:
0

In [148]:
~0b11110000


Out[148]:
-241

In [149]:
bin(~241)


Out[149]:
'-0b11110010'

In [150]:
0b11110000 | 0b00001111


Out[150]:
255

In [151]:
2>>1    #10
# 10->1


Out[151]:
1

In [152]:
2<<1    #10 -> 100


Out[152]:
4

索引切片运算


In [ ]:


In [ ]:


In [ ]:


In [ ]:

浅复制


In [153]:
a = [1,2,3]
b = a
b[0] = 3
print a, b


[3, 2, 3] [3, 2, 3]

In [154]:
import copy

In [155]:
b = copy.deepcopy(a)
b[0] = 5
print a, b


[3, 2, 3] [5, 2, 3]

In [156]:
a = [1,2,3]
b = a

In [157]:
id(a) == id(b)


Out[157]:
True

In [158]:
id(a)


Out[158]:
4369641840

In [159]:
id(b)


Out[159]:
4369641840

In [ ]: