python关闭局部变量 [英] python closure local variables

查看:90
本文介绍了python关闭局部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此答案中展示了一个单例装饰器

In this answer a singleton decorator is demonstrated as such

def singleton(cls):
    instances = {}
    def getinstance():
        print len(instances)
        if cls not in instances:
            instances[cls] = cls()
        return instances[cls]
    return getinstance

但是 instances 对于装饰的每个类都是本地的,所以我试图提高效率和使用

but instances is 'local' to each class that is decorated, so I tried to be more efficient and use

def BAD_singleton(cls):
    instances = None
    def getinstance():
        if instances is None:
            instances = cls()
        return instances
    return getinstance

@BAD_singleton
class MyTest(object):
    def __init__(self):
        print 'test'

但是,这会产生错误

UnboundLocalError: local variable 'instances' referenced before assignment

之前引用ble'instances'被称为

when m = MyTest() is called

我想我知道这应该行不通(因为实例的分配将是本地的,并且在两次调用之间会丢失),但是我确实不明白为什么我会收到此错误。

I think I understand which this should not work (as the assignment to instances will be local and be lost between calls), but I do not understand why I am getting this error.

推荐答案

错误的原因是python比我聪明,并且确定了实例是由作业本地化的,不会向上查找作业。正如@GeeTransit的评论中指出的那样,这可以在python3中通过 nonlocal

The reason for the error is python is cleverer than I am and identified that instances is made local by the assignment and does not go up-scope to find the assignment. As pointed out in the comments by @GeeTransit this is possible in python3 via nonlocal

def nonlocal_singleton(cls):
    instances = None
    def getinstance():
        nonlocal instances
        if instances is None:
            instances = cls()
        return instances
    return getinstance

@nonlocal_singleton
class MyTest(object):
    def __init__(self):
        print('test')

这篇关于python关闭局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆