【问题标题】:Python Nested Object Destructor (vs C++)Python 嵌套对象析构函数(vs C++)
【发布时间】:2018-03-02 04:33:12
【问题描述】:

假设我有两个班级:

import matplotlib.pyplot as plt

class AClass:
    def __init__(self):
        self.A = SomeStuff()
        self.B = plt.figure(1)
    def SomeOtherThings(self):
        MaybeIPlotSomeThingsToThatPlotEtc
        ....

class AnotherClass:
    def __init__(self):
        self.AClassWithinAClass = AClass()
        self.B = plt.figure(2)
    def SomeOtherThings(self):
        MaybeIPlotSomeThingsToThatPlotEtc
        ....

在 C++ 中,当我将一个对象作为指向该对象的指针放入另一个对象时,我必须,必须在析构函数中删除它,否则就是内存泄漏。

问题1:在上面的伪代码中,self.B是我需要在析构函数中删除的那种指针吗?

问题 2:变量 AClassWithinAClass 呢?这是我需要在析构函数中删除的指针,还是 python 知道在 AnotherClass 被删除时摆脱它?

我试过用谷歌搜索指针和东西 (Pointers in Python?) 但我想我很紧张,因为 python 是一种隐含的语言。

【问题讨论】:

  • 没有。 Python中没有指针,内存是为你管理的。
  • 如果你指的是__del__的析构函数,不要实现它,因为搞乱它很可能会导致内存泄漏。

标签: python pointers destructor


【解决方案1】:

在这两种情况下,您都不需要显式调用析构函数。 Python 使用垃圾收集来管理内存。为了保持这一点,它使用引用计数。 Python 会记录有多少变量引用了一个特定的对象。但是,如果 Python 有一个没有被任何东西引用的变量,它将释放内存。我当然不是 Python 内部内存管理方面的专家,但这是我的理解。

Previous StackOverflow Post

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-02
    • 1970-01-01
    • 2023-03-23
    • 2022-01-08
    • 2017-11-14
    • 1970-01-01
    • 1970-01-01
    • 2016-11-08
    相关资源
    最近更新 更多