1、调试python方法,断言(assert)
def foo(s):
n = int(s)
assert n != 0, 'n is zero!'
return 10 / n
def main():
foo('0')
assert的意思是,表达式n != 0应该是True,否则,后面的代码就会出错报'n is zero!'。
2、python函数参数带*说明
带一个星号(*)参数的函数传入的参数存储为一个元组(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
带两个星号(*)参数的函数传人的参数则存储为一个字典(dict),并且在调用是采取 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、打印接口返回
先添加前端页面 test.html:
'<div>{{data}}</div>'
然后在函数返回处调用页面返回:
return render_to_response('test.html', {‘data’: 变量})
访问页面即可获取变量返回值
4、判断变量是否数字
id = 123456
if type(id) != int:
print('id不是数字')
else:
print('id是数字')
5、修饰符@
def test(f):
print "before ..."
f()
print "after ..."
@test
def func():
print "func was called"
结果:
before ...
func was called
after ...
6、json 写入文件中缓存
#!/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、
网友评论