Python基础(四)

一 . 装饰器(很重要的一个内容)

定义:  本质是函数,(装饰其他函数)就是为其他函数添加其他功能

注意事项:a.不能修改被装饰的函数的源代码,

                  b. 不能修改被装饰的函数的调用方式。

 补充:

         a.函数就是“变量”,把函数体赋给了函数名。

         b. 高阶函数+嵌套函数>>>>装饰器

         c.高阶函数:把一个函数名当做实参传给另一个函数(不修改被装饰的函数的源代码);

                              返回值中包含函数名(不修改被装饰的函数的调用方式)。

复制代码
#一个函数名当做实参传给另一个函数
import
time def bar(): time.sleep(3) print('in the bar') def test1(func): start_time = time.time() func() #run bar stop_time = time.time() print("the func run time is %s" % (stop_time - start_time) ) #运行时间等于结束时间减去开始时间 test1(bar)

注:不大理解这个(哈哈哈)

复制代码
# 返回值中包含函数名
import
time def bar(): time.sleep(3) print('in the bar') def test2(func): print(func) return func #print(test2(bar)) bar = test2(bar) bar()
复制代码

 

 

 d.嵌套函数

函数的嵌套,在函数的内部再申明一个函数,而不是去调用
复制代码
def foo():
    print("in the foo")
    def bar():
        print("in tne bar")    #函数的嵌套,在函数的内部再申明一个函数,而不是去调用

    bar()
foo()
复制代码

 


复制代码
#局部变量与全局变量的访问次序:
x = 0 def grandpa(): x = 1 def dad(): x=2 def son(): x=3 print(x) son() dad() grandpa()
运行结果:3

复制代码

 


复制代码
 1 import time
 2 user,passwd = "xiaolaizi","abc123"
 3 #装饰器
 4 def auth(func):
 5     def wrapper(*args,**kwargs):
 6         username = input ("Username:").strip()   #strip去空格
 7         password = input("Password:").strip()
 8 
 9         if user == username and passwd == password:
10             print("\033[32;1mUser has passed authentication\033[0m")
11             res = func(*args,**kwargs)
12             print(20*'*')
13             return res
14         else:
15             exit("\033[31;1mUser has not passed authentication\033[0m")
16     return wrapper
17 def index():           #定义一个首页
18     print("welcome to index page")
19 @auth   #本地验证@auth(auth_type = "local")
20 def home():        #定义一个登陆页面
21     print("welcome to home page")
22     return "from home"
23 @auth   #远程验证@auth(auth_type = "ldap")
24 def bbs():        #定义一个论坛区页面
25     print("welcome to bbs page")
26 
27 index()
28 print(home())
29 #home()
30 bbs()
View Code
复制代码

 

 
复制代码

 

 

        

posted @   百里屠苏top  阅读(134)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示