本文介绍了可以“软引用"存在于Python中吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在其他语言(例如Java)中,对象引用可以是强",弱",软"或幻影"( http://weblogs.java.net/blog/enicholas/archive/2006/05/understanding_w.html ).

In other languages (e.g. Java), object references can be Strong, Weak, Soft or Phantom (http://weblogs.java.net/blog/enicholas/archive/2006/05/understanding_w.html).

在Python中,默认情况下引用是强"引用,而WeakRef模块则允许使用弱引用.

In Python, references are Strong by default and the WeakRef module allows weak references.

在Python中是否可以使用软引用"?

Is it possible to have "soft references" in Python?

在我的特殊情况下,我有一个创建对象的缓存,这些对象很耗时.有时可能没有对缓存对象的引用,但是如果不需要(即如果有足够的内存),我不想扔掉缓存的对象.

In my particular case, I have a cache of objects that are time-consuming to create. Sometimes there may be no references to a cached object, but I don't want to throw the cached object away if I don't have to (i.e. if memory is plentiful).

推荐答案

除了硬(又称强")&虚弱的.

Python doesn't natively offer any flavors of references besides hard (aka strong) & weak.

也就是说,此处是我大约一年前提出的softref实现.在一些需要使用的地方使用.它提供的不是真正的软引用,但是对于大多数用例来说,它是很接近的.边缘有些粗糙,但是功能齐全……尽管它依赖于内部的一些引用计数,这意味着它可能会破坏除CPython之外的任何东西.

That said, here is a softref implementation I whipped up a year or so ago which I've been using in a few places I needed one. What it provides aren't quite actual soft references, but it comes close for most use cases. It's a little rough around the edges, but is fully functional... though it relies on some reference counting internally that means it'll probably break on anything except CPython.

特别是,我专门为缓存创建昂贵的长寿命对象而编写了它……SoftValueDictionary应该正是您要寻找的东西.

In particular, I wrote it precisely for a cache of expensive-to-create long-lived objects... the SoftValueDictionary should be exactly what you're looking for.

这篇关于可以“软引用"存在于Python中吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 19:38