码迷,mamicode.com
首页 > 编程语言 > 详细

python装饰器执行机制

时间:2017-09-18 17:20:40      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:调用函数   ext   div   看到了   global   none   为什么   open   logs   

前沿:

首先是看到了单例模型,想不明白 outer中的参数 为什么能像 global的参数 一样屹立不倒。

技术分享
#单例模型
def single_model(cls):
    instance = {}
    def inner(*args, **kwargs):
        print
        if cls not in instance:
            instance[cls] = cls(*args, **kwargs)
            print cls not in instance
        return instance[cls]
    return inner


@single_model
class MyFoo(object):

    def __init__(self):
        self.name = wwt
        self.age = 12


mf1 = MyFoo()
mf2 = MyFoo()
mf1.name = asfaf
print mf2.name
print mf1 is mf2


[out:]
asfaf
True
View Code

这样我就十分奇怪了,但后来将 instance 放在 inner 中单例模型就失败了,所以问题一定在装饰器的 outer 上。

 

1 装饰器个层级之间的执行顺序

def single_model(text):
    print last_outer  + text

    def outer(func):
        instance = {}
        print instance_outer: %d % id(instance)

        def inner(*args, **kwargs):
            if func not in instance:
                instance[func] = func(*args, **kwargs)
                print instance_inner: %d % id(instance)
            return instance[func]
        return inner
    return outer


@single_model(zhhh)
def func():
    return hahahha

con1 此时此刻执行程序
[out:]
last_outer zhhh
instance_outer: 31691640
# 也就是说装饰器创建后,他会在func调用前执行。


-----------------------------------------------
con2 调用函数
abc = func()
efg = func()
print abc, efg
[out:]
last_outer zhhh
instance_outer: 30905208
instance_inner: 30905208
hahahha hahahha
# 如果在outer或更outer层定义了对象(instance)并在inner层引用,则该对象不会被GC,会存在,
# 类似于global

 

2 装饰器

python装饰器执行机制

标签:调用函数   ext   div   看到了   global   none   为什么   open   logs   

原文地址:http://www.cnblogs.com/fuzzier/p/7543711.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!