gpt4 book ai didi

python - Mathematica 中的临时变量

转载 作者:行者123 更新时间:2023-12-04 20:57:21 24 4
gpt4 key购买 nike

我为 Mathematica 编写了一个名为 MathOO 的包。简而言之,它允许您在 Mathematica 中使用面向对象,就像在 Python 中一样。请阅读 Voofie/MathOO 中的以下文章详情:

MathOO: Adding Python style Object Orientation to Mathematica with MathOO (1.0 beta launch) [Alternative to Objectica]

我遇到的问题是,我想要垃圾收集器,这样用户就不必在使用后显式删除对象。例如:

NewClass[Object1]
Object1.$init$[self_]:= Return[];

在上面两行中,我只是将 Object1 定义为一个新类,并将构造函数定义为一个空函数。如果您熟悉 Python,您应该会看到与 __init__() 的相似之处。 .

要实例化一个 Object1,我这样做:
object1 = new[Object1][]

输出是:
Out: object$13

这里,object$13 是一个临时变量。我想要的是,当没有对这个临时变量的引用时,它应该被自动删除。但它没有按预期工作。我已确定问题如下:
In:  y = Module[{x}, x[1] = 2; x]
Out: x$117

In: FullDefinition[y]
Out: y = x$117
Attributes[x$117] = {Temporary}
x$117[1] = 2

因为 y 持有 x$117 的引用,所以 x$117 还没有被删除。现在让我们通过将 y 的值设置为 1 来删除引用:
In:  y = 1;

但是,x$117 仍然存在:
In:  Definition[x$117]
Out: Attributes[x$117] = {Temporary}
x$117[1] = 2

但我预计该变量将被删除,因为它不再被引用。来自 manual Mathematica,它说:

Temporary symbols are removed if they are no longer referenced:



那么,这是 Mathematica 的错误吗?或者有什么解决方法吗?我正在使用 Mathematica 7.0。非常感谢你。

最佳答案

Mathematica 确实会进行垃圾收集Temporary没有更多引用时的变量。也就是说,您的 x$117 没有被垃圾收集有两个原因。

  • 请记住 Module使用词法作用域,因此模块变量只是“本地”的,因为它们被赋予唯一的名称“var$modnum”和TemporaryAttribute .
    既然你给了你的x一个 DownValue , 必须在 x 之前清除可以被垃圾回收。
  • 您的 y被设置为临时变量 x$...并将输出分配给 Out[] .所以还需要清除历史:Unprotect[In, Out]; Clear[In, Out]; Protect[In, Out]; .

  • 然后你的 Module示例似乎已正确收集垃圾。

    当使用你的 MathOO 包时(我昨天下载的,但还没有玩过)也许你可以设置 $HistoryLength到某个有限的数。并建议用户抑制实例化的输出 object1 = new[Object1][];

    关于python - Mathematica 中的临时变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4114136/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com