暑期经验分享
- 写在前面的话
- python代码的书写规范
- 编码
- 空行
- 空格
- 注释规范
- 命名规范
- 函数开头
写在前面的话
时间飞逝,转眼两年已经过去了,现在也已经到了忙碌奔波写论文找工作的时间了,仔细回想下之前两年的点点滴滴,除了在各种push下做了一些小项目,其他真的没有一点东西,真的惭愧。这么长一段时间的python语言的使用还是积累下来了一些东西,下面是把自己的一些愚见记录下来,希望能够给读者有一点点帮助。
python代码的书写规范
书写代码的时候一定要注意养成遵守规范的好习惯,每写一行代码都要保证遵守相应的规范,这样起码后面自己再看当年的大作的时候还是能够看得懂的。
编码
没有特殊情况,一般情况下就使用UTF-8编码。
文件头部加上# coding:utf-8。
# coding: utf-8
空行
两个函数模块之间一般是要空两行,类内函数之间需要空一行:
class
MainFunc
(
)
:
def
__init__
(
self
,
name
)
:
self
.
name
=
name
def
play_game
(
self
)
:
pass
def
main_func
(
)
:
pass
def
hello_world
(
)
:
pass
函数中,空行还可以用来分割不同的逻辑块:
def
yolo_body
(
inputs
,
num_anchors
,
num_classes
)
:
"""Create YOLO_V3 model CNN body in Keras."""
darknet
=
Model
(
inputs
,
darknet_body
(
inputs
)
)
x
,
y1
=
make_last_layers
(
darknet
.
output
,
512
,
num_anchors
*
(
num_classes
+
5
)
)
x
=
compose
(
DarknetConv2D_BN_Leaky
(
256
,
(
1
,
1
)
)
,
UpSampling2D
(
2
)
)
(
x
)
x
=
Concatenate
(
)
(
[
x
,
darknet
.
layers
[
152
]
.
output
]
)
x
,
y2
=
make_last_layers
(
x
,
256
,
num_anchors
*
(
num_classes
+
5
)
)
x
=
compose
(
DarknetConv2D_BN_Leaky
(
128
,
(
1
,
1
)
)
,
UpSampling2D
(
2
)
)
(
x
)
x
=
Concatenate
(
)
(
[
x
,
darknet
.
layers
[
92
]
.
output
]
)
x
,
y3
=
make_last_layers
(
x
,
128
,
num_anchors
*
(
num_classes
+
5
)
)
return
Model
(
inputs
,
[
y1
,
y2
,
y3
]
)
空格
在二元运算符两边各空一格[=,-,+=,==,>,in,is not, and, ……]:
a
=
b
+
c
batch_size
=
img_nums
//
batch_nums
函数的参数列表中,默认值等号两边不要添加空格:
def
train
(
batch_size
=
128
,
epoch
=
50
,
log_dir
=
'./logs'
)
:
pass
逗号和冒号只需要在后面留空格,这个在字典的定义过程中体现的最为明显:
demo_dict
=
{
'1'
:
'1'
,
'2'
:
'2'
,
'3'
:
'3'
}
注释规范
行注释,使用#开头,后面加上空格,注释一定要是有意义的话,这个是思路的解释,而不是简单复述代码:
# 将像素值转化为8位
img
*=
255
.
函数注释,使用三个双引号开头和三个双引号结尾,解释函数的作用,输入参数以及返回的参数:
def
reverse_list
(
nums
)
:
""" 反转列表 :pram nums:要反转的list :returns:返回反转之后的list,以及list的长度 """
new_nums
=
nums
[
:
:
-
1
]
return
new_nums
,
len
(
nums
)
命名规范
类名一般采用驼峰(CamelCase)命名规则,每个单词的首字母大写:
class
MainFunc
(
)
:
pass
class
HelloWorld
(
)
:
pass
函数名和变量名均全部使用小写,不同字母之间使用下划线_分割开:
def
hello_world
(
)
:
demo_dict
=
{
'1'
:
'2'
}
demo_list
=
[
]
常量则全部使用大写,字母之间使用下划线分开:
BATCH_SIZE
=
128
EPOCH
=
50
函数开头
如果要写一个能直接执行的脚本,要给脚本加一个规范的开头,如下:
# coding: utf-8
def
demo
(
)
:
print
(
'hello world'
)
if
__name__
==
'__main__'
:
demo
(
)