暑期經驗分享
- 寫在前面的話
- 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
(
)
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
