python3学习之路10函数闭包修饰器

导读:本篇文章讲解 python3学习之路10函数闭包修饰器,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

**#1. 闭包函数 -- 实现角色移动示例**
origin = (0, 0)
legal_x = [-100, 100]
legal_y = [-100, 100]

def create(pos_x=0, pos_y=0):
    def moving(direction, step):  #direction 设置移动方向(1 右/上,-1 左/下),step 设置移动距离
        nonlocal pos_x, pos_y  #为了修改外层变量值
        new_x = pos_x + direction[0] * step
        new_y = pos_y + direction[1] * step

        if new_x < legal_x[0]:
            pos_x = legal_x[0] - (new_x - legal_x[0])
        elif new_x > legal_x[1]:
            pos_x = legal_x[1] - (new_x - legal_x[1])
        else:
            pos_x = new_x
        if new_y < legal_y[0]:
            pos_y = legal_y[0] - (new_y - legal_y[0])
        elif new_y > legal_y[1]:
            pos_y = legal_y[1] - (new_y - legal_y[1])
        else:
            pos_y = new_y

        return  pos_x, pos_y
    return moving  #函数作为返回值返回不需要加(),函数只需要在定义和调用得时候需要()

move = create()
print("向右移动20步后位置是:",move([1,0],20))  #打印 向右移动20步后位置是: (20, 0)
print("向上移动120步后位置是:",move([0,1],120))  #打印 向上移动120步后位置是: (20, 80)
print("向右下角移动88步后位置是:",move([1,-1],88))  #打印 向右下角移动88步后位置是: (92, -8)

#2. 将函数作为参数传递给变量
def myfun():
    print("正在调用myfun1...")

def report(func):  #report得参数是一个函数得引用func
    print("我要开始调用函数了...")
    func() #函数得函数名就是它得引用,加()就是调用
    print("我调用完函数了...")
report(myfun)
'''打印
我要开始调用函数了...
正在调用myfun1...
我调用完函数了...
'''

#3. 闭包练习  拿函数当参数
import time
def time_master(func):
    print("开始运行程序...")
    start = time.time()
    func()
    stop = time.time()
    print("结束程序运行...")
    print(f"一共耗费了 {(stop-start):.2f} 秒")
def myfunc():
    time.sleep(2)
    print("Hello SH.")

time_master(myfunc)
'''打印
开始运行程序...
Hello SH.
结束程序运行...
一共耗费了 2.01 秒
'''

#4. 装饰器
import time
def time_master(func):
    def call_func():
        print("开始运行程序...")
        start = time.time()
        func()
        stop = time.time()
        print("结束程序运行...")
        print(f"一共耗费{(stop-start):.2f}秒")
    return call_func
@time_master  #装饰器得语法
def myfun():
    time.sleep(2)
    print("Hello SH")
myfun()
'''打印
开始运行程序...
Hello SH
结束程序运行...
一共耗费2.02秒
'''

#5. 再优化
import time
def time_master(func):
    def call_func():
        print("开始运行程序...")
        start = time.time()
        func()
        stop = time.time()
        print("结束程序运行...")
        print(f"一共耗费{(stop-start):.2f}秒")
    return call_func
def myfun():
    time.sleep(2)
    print("Hello SH")
myfun = time_master(myfun)
myfun()
'''打印
开始运行程序...
Hello SH
结束程序运行...
一共耗费2.00秒
'''

#6. 给装饰器传递参数
import time
def logger(msg):
    def time_master(func):
        def call_func():
            start = time.time()
            func()
            stop = time.time()
            print(f"{msg}一共耗费了{(stop-start):.2f}")
        return call_func
    return time_master

def funA():
    time.sleep(1)
    print("正在运行funA")

def funB():
    time.sleep(2)
    print("正在运行funB")

funA = logger(msg='A')(funA)
funB = logger(msg='B')(funB)

print(funA())
print(funB())
'''打印
正在运行funA
A一共耗费了1.01
None
正在运行funB
B一共耗费了2.00
None
'''

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/1910.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!