Ⅳ-Python函数进阶

目录

        1.多参数解析

        实参

         形参

        2.闭包

        示例一:无返回值情况

        示例二:有返回值情况

        示例三: 有参数返回值情况

        3.装饰器

        示例一:初识装饰器

        示例二:带参数的装饰器

        4.思维导图


1.多参数解析

结合上篇文章,我们得知使⽤ *args**kwargs 来调⽤函数。

*args:元组
**kwargs:字典

实参

使用普通参数方式:
res(1, 2, 3)
# 元组方式传递
def res(arg1,arg2,arg3):
    print("arg1:",arg1)
    print("arg2:",arg2)
    print("arg3:",arg3)

nums = (1,2,3)
res(*nums)
#以字典方式传递
myargs = {
    "arg1":1,
    "arg2":2,
    "arg3":3
}
res(**myargs)

 形参

#函数⾥同时使⽤所有这三种参数, 顺序是这样的:
def text_kwargs(first, *args, **kwargs):
    print('Required argument:',first)
    print('args type',type(args))#tuple元组
    print('kwargs',type(kwargs))#kwargs字典
    for v in args:
        print('Optional argument(args):',v)
    for k , v in kwargs.items():#value keys items
        print('Optional argument %s (kwargs): %s'%(k ,v))


text_kwargs(1)
text_kwargs(1,2,3,4)
text_kwargs(1,x=1,y=2)
text_kwargs(1,2,3,4,x=1,y=2)

2.闭包

如果在一个函数的内部定义了另一个函数,外部的我们叫他外函数内部的我们叫他内函数。

  • 闭包函数:声明在一个函数中的函数,叫做闭包函数。

  • 闭包:

    • 在一个外函数中定义了一个内函数

    • 内函数里运用了外函数中声明的参数或变量

    • 并且外函数的返回值是内函数的引用。这样就构成了一个闭包。

闭包应用于:数据共享

示例一:无返回值情况

def hello():
    def say():
        print("hello python")

 注意:hello代表函数本身;hello()代表函数的返回值。

示例二:有返回值情况

def hello():
    def say():
        print("hello python")
    return say

 注意:此时可以发现hello()方法的返回值是say方法,也就是它的内部函数。

res=hello
hello()

示例三: 有参数返回值情况

def counter(initial_value=0):
    #count[0] = 10
    count = [initial_value]#使用列表存储计数值,以使用内部函数中修改

    def increment():
        #增加计数
        count[0] += 1
        return count[0]

    def decrement():
        #减少计数
        count[0] -= 1
        return count[0]

    #返回两个内部函数
    return increment,decrement

#创建闭包实例
inc ,dec = counter(10)

#使用闭包
print(inc()) #输出11
print(dec()) #输出10

3.装饰器

装饰器是闭包的一种应用。

        特点:

                ①装饰器用于拓展原来函数功能的一种函数,它的返回值也是一个函数。

                ②用更改原函数的代码前提下给函数增加新的功能。

# 开启事务
核心业务处理
# 提交/回滚事务

可以理解为Spring中的AOP。

示例一:初识装饰器

@表达上,<表达式>一般为装饰器

from functools import wraps
def transaction(func):
#@wraps(func)的作用: 不改变使用装饰器原有函数的结构
    @wraps(func)
    def wrapper():
        print("打开连接")
        func()
        print("关闭连接")
    return wrapper


@transaction
def hello():
    print("hello python")
    
hello()
print(hello.__name__)

注意:当使用装饰器@Transaction修饰方法时,hello.__name__返回的方法名称就不是当前hello方法了,而是被装饰器中的wrapper方法所取代。  

示例二:带参数的装饰器

装饰器中可以传入参数,先形成一个完整的装饰器,然后再来装饰函数,当然函数如果需要传入参数也 是可以的,用不定长参数符号就可以接收。

def logg(level:str="debug"):#套壳
    print('level=',level)
    def outer_wrapper(func):
        def inner_wrapper( *args, **kwargs):
            date = str(datetime.datetime.now())
            print(f'【{level}】{date}{func.__name__}函数被调用')
            return func( *args, **kwargs)
        return inner_wrapper
    return outer_wrapper


@logg("info")
def hello():
    print('hello python')

@logg()
def exam1(n1:int,n2:int):
    print('hello exam1')

@logg()
def exam2():
    print('hello exam2')

hello()
exam1(1,2)
print(exam2())

注意:@logg装饰器带括号和不带括号的区别

  1. @logg不带括号,hello方法名作为参数传入,则在level参数接收到的是hello方法;

  2. @logg()带括号,则使用logg中的level默认参数或者传入参数覆盖level默认参数;

def logging(logfile='out.txt'):
    def decorator(func):
        def wrapped_function(*args, **kwargs):
            log_string = func.__name__ + "被调用了"
            # 打开logfile,并写⼊内容
            with open(logfile, 'a') as opened_file:
                # 现在将⽇志打到指定的logfile
                opened_file.write(log_string + '\n')
        return wrapped_function
    return decorator

@logging()
def hello():
    pass

hello()

4.思维导图

----------------------------------------------------------------------------------------♥-------------------------------------------------------------------------------------

往期Python内容:

Ⅰ-Python入门与基本语法

Ⅱ-Python运算符(进阶语法)

Ⅲ-python函数的使用

  • 37
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值