python之路4

本节内容:
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 匿名函数 只能写三元运算

还有filterfilter有过滤数据的作用如下
res = filter(lambda n:n>5,range(10))
for i in res:
    print(i)
    
这样就只显示了10以内大于5的数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值