众所周知,每种语言都有他自己的写作风格,Python也不例外。那今天的特别篇,我就给大家讲解Python写作风格(以下称PEP 8)
1、保留适当的空格。
在PEP 8中,运算符号左右(有特例)、判断符号之后(有特例)、逗号之后(也有特例)、赋值符号之后(还是有特例)、冒号之后加上空格。
>>> #好的写法:
>>>
>>> a = 10 + 3
>>> b = (10, 20, 30)
>>> c = 10 + 2
>>> if a == c: print("Variable a and variable c are same.")
>>>
>>> #不好的写法:
>>> a=10+3
>>> b=(10,20,30)
>>> c=10+2
>>> if a==c:print("Variable a and variable c are same.")
但是也不能保留过多空格。
>>> #好的写法:
>>>
>>> a = (10,)
>>> b = a[0]
>>> c = 10*5 + 10*3
>>> d = True
>>> e = False
>>> f = (d!=e) == (d==e)
>>> print("aaaaaa", "bbbbbb", sep="***")
aaaaaa***bbbbbb
>>>
>>> #不好的写法:
>>> a = (10, )
>>> b = a [0]
>>> c = 10 * 5 + 10 * 3
>>> d = True
>>> e = False
>>> f = (d != e) == (d == e)
>>> print("aaaaaa", "bbbbbb", sep = "***")
aaaaaa***bbbbbb
下面不好的写法就更不行了:
>>> #好的写法:
>>> a = 10
>>> b = 10
>>> c = 100000000
>>>
>>> #不好的写法:
>>> a = 10
>>> b = 10
>>> c = 100000000
(谁这样写啊!)
有人可能会问:为什么运算符号左右有时候要空格,有时候不要空格呢?
在PEP 8中,我们在拥有不同运算级别的算式中,在运算级别较低的运算符旁添空格。
2、适当换行。
>>> #好的写法:
>>>
>>> turtle_list1 = ["Reeves' Turtle",
"Chinese Stripe-necked Turtle",
"Yellow Pond-turtle",
"Red-necked pond turtle",
"Beal's eyed turtle",
"Four-eyed Turtle",
"Big-headed Turtle"]
>>>
>>> turtle_list2 = [
"Reeves' Turtle",
"Chinese Stripe-necked Turtle",
"Yellow Pond-turtle",
"Red-necked pond turtle",
"Beal's eyed turtle",
"Four-eyed Turtle",
"Big-headed Turtle"
]
>>>
>>> #不好的写法
>>>
>>> turtle_list3 = ["Reeves' Turtle", "Chinese Stripe-necked Turtle", "Yellow Pond-turtle", "Red-necked pond turtle","Beal's eyed turtle", "Four-eyed Turtle", "Big-headed Turtle"]
>>>
>>> turtle_list4 = [
"Reeves' Turtle",
"Chinese Stripe-necked Turtle",
"Yellow Pond-turtle",
"Red-necked pond turtle",
"Beal's eyed turtle",
"Four-eyed Turtle",
"Big-headed Turtle"]
>>> #好的写法:
>>>
>>> a = 10 \
+ 10 \
+ 20 \
+ 9
>>>
>>> #不好的写法:
>>>
>>> b = 10 +\
10 +\
20 +\
9
3、命名
在符合命名规则后,变量、列表、元组、字典、集合、函数和方法建议首字母小写,类建议首字母大写。如有空格,用下划线连接。
>>> #好的写法:
>>>
>>> class Good_class():
def good_method(self):
print("This class and this method are good.")
>>> def good_function():
print("This function is good")
>>> str_ = "Python"
>>>
>>> list_ = [1, 2, 3]
>>> tuple_ = (1, 2, 3)
>>> dict_ = {"0": 0, "1": 1, "2": 2}
>>> set_ = set([1, 2, 3])
>>>
>>> #不好的写法:
>>> class bad_class():
def Bad_method(self):
print("This class and this method are bad.")
>>> def Bad_function():
print("This function is bad")
>>> Str_ = "Python"
>>>
>>> List_ = [1, 2, 3]
>>> Tuple_ = (1, 2, 3)
>>> Dict_ = {"0": 0, "1": 1, "2": 2}
>>> Set_ = set([1, 2, 3])
4、导入
在导入库的时候,PEP 8建议一行导入一个,而不是一行导入N个。
>>> #好的写法:
>>>
>>> import numpy
>>> import matplotlib
>>>
>>> #不好的写法:
>>>
>>> import numpy, matplotlib
但在一个库中导入N个模块可以写在一行。
>>> from ramdom import randint, choice
本人也还是一个Python渣渣,对PEP 8还不是特别理解,请各位大佬批评指正。
我是谢pro,886~