首页 > 其他分享 >概要12

概要12

时间:2022-10-11 21:12:08浏览次数:44  
标签:index 12 概要 func time print def 函数

今日内容回顾

目录

  • global与nonlocal
  • 函数名的多种用法
  • 闭包函数
  • 装饰器简介
  • 装饰器推导流程
  • 装饰器模板
  • 装饰器语法糖

global与nonlocal

money = 666
def index():
    global money  #局部修改全局变量 需要使用关键字声明
    money = 123
index()
print(money)  # 123
'''
global 在局部名称空间直接修改全局名称空间的数据
'''
def index():
    name = 'jason'
    def inner():
        nonlocal name  #内部局部修改外部局部
        name = 'kevin'
    inner()
    print(name)  # name就是kevin 不加声明则name就是jason 把握函数定义原则函数在定义阶段就已经把名字的查找顺序固定死了
index()
'''
nonlocal 在内部名称空间修改局部名称空间中的数据
'''

name_list = ['jason', 'kevin']
def index():
    name_list.append('oscar')
index()
print(name_list)  # ['jason', 'kevin', 'oscar'] 当是可变类型使用了内置方法局部可以直接往全局列表里添加数据值

函数名的多种用法

函数其绑定的也是一块内存地址 只不过该地址里面存放的不是数据值而是一段代码 函数名加括号就会找到该代码并执行
# 用法1:函数名可以当做变量名赋值
def index():pass
res = index
res()  # 本质就是在调用index函数
# 用法2:函数名可以当做函数的参数
def index():
    print('from index')
def func(a):
    print(a)
    a()
func(index)  # 打印函数名index ——> <function index at 0x00000159E2A660D0>然后再打印from index
# 用法3:函数名可以当做函数的返回值
def index():
    print('from index')
def func():
    print('from func')
    return index
res = func()  # 先执行func()打印from func再返回index赋值给变量名res
print(res)  # 此时变量名res指的是index函数内存地址打印的是内存地址
res()  # 相当于index加括号调用函数index函数体代码

def index():
    print('from index')
    def func():
        print('from func')
    return func
res = index()
print(res)
res()
# 用法4:函数名可以当做容器类型的数据
容器类型指的是可以存放多个数据的数据类型
def register():
    print('注册功能')
def login():
    print('登入功能')
def withdraw():
    print('提现功能')
def transfer():
    print('转账功能')
def shopping():
    print('购物功能')
func_dict = {
    '1': register,
    '2': login,
    '3':withdraw,
    '4':transfer,
    '5':shopping
}
whie True:
    print('''
    1.注册功能
    2.登入功能
    3.提现功能
    4.转账功能
    5.购物功能
    ''')
    choice = input('请选择功能项>>>:').strip()
    # 判断用户输入的编号在不在字典的K中
    if choice in func_dict:
        # 根据键获取值(函数名)
        func_name = func_dict.get(choice)
        # 函数名加括号调用
        func_name
    else:
        print('功能编号不存在')
	# 下列代码的弊端在于功能较多时 代码过于复杂
    # if choice == '1':
    #    register()
    # elif choice == '2':
    #   login()
    # elif choice == '3':
    #   withdraw()
    # elif choice == '4':
    #    transfer()
    # elif choice == '5':
    #   shopping()
    # else:
    #   print('功能编号不存在')

闭包函数

'''
定义在函数内部的函数 并且用到了外部函数名称空间中的名字
	1.定义在函数内部
	2.用到外部函数名称空间中的名字
'''
def idex():
    name = 'jasn'
    def inner():
        print(name)

闭包函数实际应用>>>:是另一种给函数体代码传参的方式!!!

# 给函数体代码传参的方式1:代码里面缺什么变量名形参里面就补什么变量名
def register(name ,age):
    print(f'''
    姓名:{name}
    年龄:{18}
    ''')
register('jason', 18)
# 给函数体代码传参的第二种方式:闭包函数
def outer(name, age):
    # name = 'jason'
    # age = 18
    def register():
        print('''
        姓名:{name}
        年龄:{age}
        ''')
    return register
res = outer('jason', 18)  # outer函数调用name=jason age=18返回值是register函数名赋值给res变量名
res()  # res加括号相当于register加括号调用
res()  # 并且res加括号可以反复调用
res = outer('kevin', 28)
res()
res()

装饰器简介

1.概念
	什么叫装饰器?
    	在不改变被装饰对象原代码和调用方式的情况下给被装饰对象添加新的功能
2.本质
	并不是一门新的技术 而是由函数参数、名称空间、函数名多种用法、闭包函数组合到一起的结果
3.口诀
	对修改封闭 对扩展开放
4.储备知识
	时间相关操作
    import time
    print(time.time())  # 时间戳(距离1970-01-01零时零分所经历的秒数)
    time.sleep(3)
    print('学习使我快乐')
    
    
    count = 0
    循环之前先获取时间戳
    start_time = time.time()
    while count < 100:
        print('终生学习')
        count += 1
    end_time = time.time()
    print('循环消耗的时间:', end_time - start_time)

装饰器推导流程

'''在不改变被装饰对象原代码和调用方式的情况下给被装饰对象添加新的功能'''
import time

def index():
    time.sleep(1)
    print('from index')
def home():
    time.sleep(2)
    print('from home')
'''1.直接在调用index函数的前后添加代码'''
start_time = time.time()
index()
end_time = time.time()
print('函数index的执行时间为:', end_time - start_time)
'''2.index调用的地方较多 代码不可能反复拷贝——>想到相同的代码需要在不同位置反复执行——>想到函数'''
def get_time():
    start_time = time.time()
    index()
    end_time = time.tiem()
    print('函数index的执行时间为:', end_time - start_time)
get_time()
'''3.函数体代码写死了 只能统计index的执行时间 如何才能做到统计更多的函数运行时间 直接传参变换统计的函数'''
def get_time(xxx):
    start_time = time.time()
    xxx()
    end_time = time.tiem()
    print('函数的执行时间为:', end_time - start_time)
get_time(index)
get_time(home)
'''4.虽然实现了一定的兼容性 但是并不符合装饰器的特征 第一种传参不写 只能考虑闭包'''
def outer(xxx):
    # xxx =index
    def get_time():
        start_time = time.time()
        xxx()
        end_time = time.time()
        print('函数的执行时间为:', end_time - start_time)
     return get_time
res = outer(index)
res()
res1 = outer(home)
res1()
'''5.调用方式还是不对 如何变形——>变量名赋值绑定'''
def outer(xxx):
    def get_time():
        start_time = time.time()
        xxx()
        end_time = time.time()
        print('函数的执行时间为:', end_time - start_time)
    return get_time
res = outer(index)  # 赋值符号左边是一个变量名 可以随意命名
res1 = outer(index)
l1 = outer(index)
index = outer(index)
index()
home = outer(home)
home()
'''6.上述装饰器只能装饰无参函数 兼容性太差'''
def func(a):
    time.sleep(0.1)
    print('from func', a)
    
def func1(a, b):
    time.sleep(0.2)
    print('from func1', a, b)
    
def func2():
    time.sleep(0.3)
    print('from func2')

def outer(xxx):
    def get_time(a, b):
        start_time = time.time()
        xxx(a, b)
        end_time = time.time()
        print('函数的执行时间为:', end_time - start_time)
    return get_time
func1 = outer(func1)
func1(1, 2)
func = outer(func)
func(1)
func2 = outer(func2)
fucn2()
'''7.装饰器的函数不知道有没有参数以及有几个参数 如何兼容'''
def func(a):
    time.sleep(o.1)
    print('from func', a)

def func1(a, b):
    time.sleep(0.2)
    print('from func1', a, b)
def ouet(xxx):
    def get_time(*args, **kwargs):  # get_time(1, 2, 3) args=(1,2,3)
        start_time = time.time()
        xxx(*args, **kwargs)  # xxx(*(1, 2, 3))  xxx(1, 2, 3)
        end_time = time.time()
        print('函数的执行时间为:', end_time - start_time)
     return get_time
func = outer(func)
func(123)
func1 = outer(func1)
func1(1, 2)
'''8.如果被装饰的函数有返回值'''
def func(a):
    time.sleep(0.1)
    print('from func', a)
    return 'func'
def func1(a, b):
    time.sleep(0.2)
    print('from func1', a, b)
    return 'func1'

def outer(xxx):
    def get_time(*args, **kwargs):
        start_time = time.time()
        res1 = xxx(*args, **kwargs)
        end_time = time.time()
        print('函数执行时间为:', end_time - start_time)
        return res1
    return get_time

func = outer(func)
res = func(123)
print(res)

func1 = outer(func1)
res = func1(123, 123)
print(res)

装饰器模板

---------------------------务必掌握----------------------------
def outer(func):
    def inner(*args, **kwargs):
        print('执行函数前可以添加的额外功能')
        res = func(*args, **kwags)  # 执行被装饰的函数
        print('执行函数之后可以添加的额外功能')
        return res  # 将被装饰函数执行之后的返回值返回
    return inner

装饰器语法糖

def outer(func_name):
    def inner(*args, **kwargs):
        print('执行被装饰对象之前可以做的额外操作')
        res = func_name(*args, **kwargs)  # 执行被装饰的函数
        print('执行被装饰对象之后可以做的额外操作')
        return res  # 将被装饰的函数执行之后的返回值返回
    return inner
'''
语法糖会自动将下面紧挨着的函数名当做第一个参数自动传给@函数调用
'''

@outer  # 相当于 func = outer(func)
def func():
    print('from func')
    return 'func'

'''
装饰器语法糖书写规范
	语法糖必须紧贴着在被装饰对象的上方
装饰器语法糖内部原理
	会自动将下面紧贴着的被装饰对象名字当做参数传给装饰器函数调用
'''

@outer  # 相当于 index = outer(index)
def index():
    print('from index')
    return 'index'

func()
index()

标签:index,12,概要,func,time,print,def,函数
From: https://www.cnblogs.com/xiao-fu-zi/p/16782569.html

相关文章

  • Python学习路程——Day12
    Python学习路程——Day12global与nonlocal'''global: 是一个内置方法,它的作用是在函数体内声明一个全局名称空间,让这个全局名称空间可以在函数体内的局部名称空间中被......
  • 12、Java——对象和类案例代码详解
    ❤️ 目录​​⛳️案例一、写一个人的类​​​​⛳️案例二、写一个汽车类​​​​⛳️案例三、定义一个描述坐标点的类​​​​⛳️案例四、定义一个圆类型​​​​⛳️案例五、......
  • Python基础12
    今日内容概要global与nonlocal函数名的多种用法闭包函数装饰器简介装饰器推导流程装饰器模板装饰器语法糖今日内容详细global与nonlocal'''通过global声明可......
  • 【转】如何解决win10无法访问计算机名访问共享但能用IP的问题 转自:https://www.xpwin
    如何解决win10无法访问计算机名访问共享但能用IP的问题转自:https://www.xpwin7.com/jiaocheng/12788.html经过很长时间的摸索,折腾。终于解决了WIN10可以访问IP,但不能访问......
  • 512多表关系介绍和513多表关系介绍一对多关系实现
    多表关系介绍1.一对一(了解):如:人和身份证。分析:一个人只有一个身份证,一个身份整只能对应一个人2.一对多(多对一):如部门员工。分析:一个部门有多个员工,一个员工只能,对应一个部......
  • uva127 -
    Timelimit:3.000seconds限时:3.000秒 Problem问题Youaretosimulatetheplayingofgamesof"Accordian"patience,therulesforwhichareasfollows:模拟玩......
  • CF1420D & gym102012 G
    CF1420D:注意到任意条线段的交集如果非空的话必定是一条线段,且这条线段的左端点一定是某条线段的左端点。很明显先将线段离散化,然后去枚举相交的线段的左端点。我们设\(......
  • CF1237F 题解
    传送门题意给你一个\(n\timesm\)的棋盘,上面已经放了\(k\)个\(1\times2\)的骨牌。对于一个骨牌的每个格子,不能有其他骨牌的格子与它在同一行、同一列。你可以......
  • leetcode-128. 最长连续序列
    128.最长连续序列首先去重,直接把数组装入set集合即可然后,设集合中的某个数为a。遍历集合set假如这个集合中,存在a-1,说明a不是一个序列的起始值,跳过如果不存在a......
  • JVMVRFY012 stack shape inconsistent
    Causedby:java.lang.VerifyError:JVMVRFY012stackshapeinconsistent;class="brave"/sampler/Sampler$$EnhancerBySpringCGLIB$$71f9816b,method=<init>()V,pc=0......