Python函数闭包装饰器

x=2222
print(x)
def func1():
    x=65842
    def func2():
        x=65412
        print(x)
    func2()
func1()
print(x)
2222
65412
2222

global:调用全局变量

x=8888
def func1():
    def func2():
        global x
        x=10000000
    func2()
func1()
print(x)
10000000

local:调用外部变量

def f1():
    x=1
    def f2():
        nonlocal x
        x=666
        print(x)
    f2()
f1()
666

闭包函数:

1.内部函数

2.包含对外部作用域而非全局作用域的引用

闭包函数特点:

1.自带作用域

2.延迟计算

closure:

name='alex'
def func():
    name='egon'
    x=1000000000000000000000
    def bar():
        print(name)
        print(x)
        a=1
        b=2
    return bar
f=func()
print(f.__closure__[0].cell_contents)
print(f.__closure__[1].cell_contents)
egon
1000000000000000000000

例子:

name='lyp'
def func1():
    name='xiaobai'
    def func2():
        print(name)
    return func2
func1=func1()
func1()
xiaobai

money=8000
def func1():
    money=6000
    def mo_info(name):
        print('%s有%s钱'%(name,money))
    mo_info('xiaobai')
func1()
xiaobai有6000钱

def f0():
    name='henbai'
    def f1():
        money=6666
        def f2():
            print('xiaobai has %s'%(money))
            print(name)
        return f2
    return f1
f0()()()
xiaobai has 6666
henbai

装饰器:任意可调用对象,被装饰的对象也可以任意可调用对象

功能:在不修改被修饰对象源代码以及调用方式的前提下为其添加新功能

原则:

1.不修改源代码

2.不修改调用方法

目标:添加新功能

 

装饰器的语法:在被装饰对象的正上方的单独一行,@装饰器名字(将函数作为参数传给装饰器)

执行顺序是自上而下,计算顺序是自下而上

from urllib.request import urlopen
def info(url):
    def pa_pr():
       return urlopen(url).read()
    return pa_pr
pa_pr=info('http://www.baidu.com')
print(pa_pr())

import random
import time
def index():
    time.sleep(random.randrange(1,4))
    print('welcome to the page')
def sp_time(haha):
    def time_d():
        start_time=time.time()
        haha()
        stop_time=time.time()
        print('runtime is %s'%(stop_time-start_time))
    return time_d
index=sp_time(index)
index()

 

posted @ 2017-06-14 19:17  吃柚子的小白  阅读(144)  评论(0编辑  收藏  举报