为什么执行函数后instances变量没有丢失? [英] Why isn't the instances variable lost after executing the function?

查看:28
本文介绍了为什么执行函数后instances变量没有丢失?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常,我希望在执行该函数后会丢失一个函数变量.在下面的情况下,我按照一些教程编写了一个单例,但它可以工作.有人可能会争辩说,每次调用 singleton 函数时,instances 都应该再次为空.

def 单例(cls):实例 = {}def get_instance(*args, **kwargs):如果 cls 不在实例中:实例[cls] = cls(*args, **kwargs)返回实例[cls]返回 get_instance@单身人士类 cls(对象):经过

我的假设是,如果不是动态函数 get_instance 被返回,其中存储了对变量的引用,那么 instances 确实会丢失它仍然可用.这导致 instances 继续存在.

这种解释正确吗?对于每个 get_instance 调用,都有一个 instances 的单独实例"是否也正确?它们不能与每个 singleton 调用相同,但有一个新的 instances = {}.

解决方案

这个:

<预><代码>>>>@单身人士>>>类 cls(对象):... 经过

相当于:

<预><代码>>>>类 cls(对象):... 经过>>>cls = 单例( cls )

singleton 只在你装饰它的每个类中运行一次(不是每个实例化).它返回的函数是每次singleton被调用时get_instance的不同实例,每次实例化运行一次.因此,即使您尝试实例化许多 cls 对象,也只会创建一个 instances 对象.

注意上面之后实际上是什么类型的可调用cls:

<预><代码>>>>类<函数get_instance at 0x0000000002352B38>

instances 对象直到它们不再可访问时才会被回收,因为 Python 使用 垃圾收集.只要关闭get_instance函数,它就被认为是可访问的 在它上面,是可达的.

Normally, I would expect a function variable to be lost after execution of that function. In the below case where I wrote a Singleton following some tutorials, it works, though. One could argue that instancesshould be empty again everytime the singleton function is called.

def singleton(cls):
    instances = {}
    def get_instance(*args, **kwargs):
        if cls not in instances:
            instances[cls] = cls(*args, **kwargs)
        return instances[cls]
    return get_instance

@singleton
class cls(object):
    pass

My assumption is that indeed instances would be lost if it weren't the case that a dynamic function get_instanceis returned in which a reference to the variable is stored so that it is still available. This leads to the fact that instances continues existing.

Is that interpretation correct? Is it also correct that for every get_instance call there is a separate "instance" of instances? They cannot be the same as for every singleton call there is a fresh instances = {}.

解决方案

This:

>>> @singleton
>>> class cls(object):
...    pass

Is equivalent to this:

>>> class cls(object):
...    pass
>>> cls = singleton( cls )

singleton is run only once per class you decorate it with (not per instantiation). The function it returns, which is a different instance of get_instance for every time singleton is called, is run once per instantiation. Thus only one instances object is created even when you attempt to instantiate many cls objects.

Note what sort of callable cls actually is after the above:

>>> cls
<function get_instance at 0x0000000002352B38>

The instances objects are not reclaimed until it they are no longer reachable because Python uses garbage collection. It is considered reachable as long as the function get_instance, which closes over it, is reachable.

这篇关于为什么执行函数后instances变量没有丢失?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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