本节内容:
1、函数
2、匿名函数
一、函数
如我现在有个写日志的需求,我可以用函数来实现
def logger():
with open('logger.txt',"a") as f:
f.write('end action\n')
def test1():
print('in the test1')
logger()
def test2():
print('in the test2')
logger()
def test3():
print('in the test3')
logger()
test1()
test2()
test3()
# 运行的话会自动将,将end action写到 a.txt文件里。
还可以为他加上一个时间
import time
def logger():
time_format = '%Y-%m-%d %X' #打印现在时间
time_current = time.strftime(time_format)
with open('a.txt',"a") as f:
f.write('%s end action\n' %time_current)
def test1():
print('in the test1')
logger()
def test2():
print('in the test2')
logger()
def test3():
print('in the test3')
logger()
test1()
test2()
test3()
def test1():
print('in the test1')
def test2():
print('in the test2')
return 0
def test3():
print('in the test3')
return 1,'hello',['luozhixiang','zhouyangqing'],{'name':'could'}
x = test1()
y = test2()
z = test3()
print(x)
print(y)
print(z) #返回多个值时,,返回的是一个元组
(1, 'hello', ['luozhixiang', 'zhouyangqing'], {'name': 'could'})
#给函数传参数。。。
def test(x,y,z):
print(x)
print(y)
print(z)
test(3,y=2,z=4)
必须要这类指定
位置参数不能在关键字参数的前面
如果是要传多个参数
def test(*args):
print(args)
test(1,2,3,4,5,6) #可传任意多个值
test(*(1,2,3,4,5)) # args=tuple([1,2,3,4,5])
将位置参数转换成了一个元组的形式返回
还有一种**kwargs
def test3(name,**kwargs):
print(name)
print(kwargs)
test3('could',age=20,sex='m') #必须这么写
could
{'age': 12, 'sex': 'm'}
将接收到的参数转换成了 key value的子类类型返回了
二、匿名函数
匿名函数,调用完之后就会被内存删除。
(lambda n:print(n))(5)
结果当然是5了
如lambda 匿名函数 只能写三元运算
还有filter, filter有过滤数据的作用如下
res = filter(lambda n:n>5,range(10))
for i in res:
print(i)
这样就只显示了10以内大于5的数

被折叠的 条评论
为什么被折叠?



