Day08-函数(3)

网友投稿 700 2022-09-08

Day08-函数(3)

Day08-函数(3)

import functools#偏函数def demo(a,b,c,d): print(a,b,c,d)# def partital_demo(a,b):# demo(a,b,3,4)# partital_demo(1,2)#实现偏函数# #固定前两个# demo = functools.partial(demo,5,6)# demo(10,50)# #固定后两个# demo=functools.partial(demo,c=3,d=5)# demo(1,2)#固定任意参数demo= functools.partial(demo,b=5,c=6)demo(a=1,d=1)# 变量作用域:能够引用变量的代码段就叫做这个变量的作用域# 1 if while try-except 这些不引入新的作用域# if 3 > 0:# a = 1# print(a)# 全局作用域:在所有的函数外定义变量# 范围:从定义开始,到本文件结束 中间处处可见a = 3def demo(): a = 5 print("demo", a) a = 5 # 局部作用域,局部变量;范围:整个函数体 print(a)demo()print(a)# 内部函数def test(): c = 10 # 闭包作用域 :从定义开始到结束 # 内部函数 def inner(): # 作用域是局部作用域 b = 10 print("inner", b) inner()inner() # 不能在外部引用内部函数 报错test()# 内建作用域:所有文件可用,系统函数、变量都是内建作用域print(max(1,2,3))## n内键作用预> 全局作用域>闭包作用域>局部作用域a = 3c = 6def outter(): a = 1 b = 3 print("outter",a,b) def inner(): b = 5 print("inner",b) print("c=",c) print("a=",a) inner()# 变量查找规则:从变量引用的地方开始向上找,找离他最近的变量outter()# 在函数里无法直接修改全局变量a = 10print(id(a))def test(): global a #告诉python解释器,以下引用的是全局变量,并可以修改 # a+=1 # print(id(a)) a = 10 print(id(a)) print(a) #6test()print(a) #6def outter(): c= 10 def inner(): nonlocal c #专门用于修改闭包作用域 c+=1 #不允许直接修改闭包作用域的变量 print(c) inner()outter()def outter():#外部函数 a = 1 def inner(): #内部函数 print(a) inner()outter()## def outter():#外部函数# a = 1# def inner(): #内部函数# print("inner",a)# return inner# #得到内部函数地址# res = outter()# res() #调用内部函数

#要增强功能的函数def eat(): print("我喜欢吃水果")#装饰器# 参数:必须要把增强的函数传进来def magic(func): def inner(): func() #调用原来的函数 #增强的功能 print("我喜欢吃炸鸡") print("我喜欢吃山珍海味") return innereat = magic(eat)eat()#装饰器# 参数:必须要把增强的函数传进来def magic(func): def inner(): func() #调用原来的函数 #增强的功能 print("我喜欢吃炸鸡") print("我喜欢吃山珍海味") return inner@magic #@外部函数 eat = magic(eat)#要增强功能的函数def eat(): print("我喜欢吃水果")eat()#装饰器# 参数:必须要把增强的函数传进来def magic(func): def inner(tmp): func(tmp) #调用原来的函数 #增强的功能 print("我喜欢吃炸鸡") print("我喜欢吃山珍海味") return inner@magic #@外部函数 eat = magic(eat)#要增强功能的函数def eat(food): print("我喜欢吃{}".format(food))eat("臭豆腐")#装饰器# 参数:必须要把增强的函数传进来def check_login(func): def inner(password): if password == '123': func(password)#执行原来功能 else: print("密码错误,重新输入") return inner #外部函数的返回值@check_login #@外部函数 forum = check_login(forum)#要增强功能的函数def forum(password): print("发帖:印度")@check_logindef comment(password): print("韩国人更厉害")forum('123')

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:小程序插件版本太低怎么办?微信小程序插件版本低有何解决方法?
下一篇:Python小白的数学建模课-B2. 新冠疫情 SI模型
相关文章

 发表评论

暂时没有评论,来抢沙发吧~