1拢蛋、調(diào)試python方法鳍徽,斷言(assert)
def?foo(s):
????n?=?int(s)
????assert?n?!=?0,?'n?is?zero!'
????return?10?/?n
def?main():
????foo('0')
assert的意思是茬暇,表達(dá)式n?!=?0應(yīng)該是True,否則寡喝,后面的代碼就會(huì)出錯(cuò)報(bào)'n?is?zero!'糙俗。
2、python函數(shù)參數(shù)帶*說(shuō)明
帶一個(gè)星號(hào)(*)參數(shù)的函數(shù)傳入的參數(shù)存儲(chǔ)為一個(gè)元組(tuple)
def function_with_one_star(*t):
????print(t, type(t))
function_with_one_star(1, 2, 3)
(1,2,3) <class 'tuple'>
--------------------------------------------------------------------------------------------------
def?foo(x,*args):
????print(x)
????print(args)
?foo(1,2,3,4,5)#其中的2,3,4,5都給了args
帶兩個(gè)星號(hào)(*)參數(shù)的函數(shù)傳人的參數(shù)則存儲(chǔ)為一個(gè)字典(dict)预鬓,并且在調(diào)用是采取 a = 1, b = 2, c = 3 的形式巧骚。
def function_with_two_stars(**d)
????print(d, type(d))
function_with_two_stars(a = 1, b = 2, c = 3)
{'a': 1, 'c': 3, 'b': 2} <calss 'dict'>
3、打印接口返回
先添加前端頁(yè)面 test.html:
'<div>{{data}}</div>'
然后在函數(shù)返回處調(diào)用頁(yè)面返回:
return render_to_response('test.html', {‘data’: 變量})
訪問(wèn)頁(yè)面即可獲取變量返回值
4珊皿、判斷變量是否數(shù)字
id = 123456
if type(id) != int:
? ? ? ? print('id不是數(shù)字')
else:
? ? ? ? print('id是數(shù)字')
5网缝、修飾符@
def?test(f):??
????print?"before?..."??
????f()??
????print?"after?..."??
@test??
def?func():??
????print?"func?was?called"??
結(jié)果:
before?...??
func?was?called??
after?...?
6、json 寫(xiě)入文件中緩存
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import json
new_dict = {
? ? ? ? "project" : "test",
? ? ? ? "timestamp" : "201805161457",
? ? ? ? "status" : "1",
}
filename = ''
with open('filename', 'w') as f:
? ? json.dump(new_dict,f,ensure_ascii=False)
? ? print('success')
讀取文件json:
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import json
filename = ''
with open(filename, 'r') as load_f:
? ? load_dict = json.load(load_f)
? ? print(load_dict)
7蟋定、