在用python设计自定义库时,如何正确地优化内存管理?

2024-10-01 15:42:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用python2.7创建一个库。因为我要多次这样调用这个库(以及其他类似的库),所以我需要确保我没有创建一堆对象(比如下面的gm),这些对象在不再需要时会浪费内存。你知道吗

但是,我有点困惑的是,在我的代码中,gm对象仍然存在于with之外:

import mylib
with mylib.GeneralMethods() as gm:
    print gm.say_hello()
>>> hello world

print gm # this is no longer needed, but still exists...
>>> <mylib.GeneralMethods object at 0x10f9c5bd0>

在设计和调用我的库时,我能做些什么来进一步优化内存管理吗? 我不想让散乱的对象吞噬记忆,比如gm。你知道吗

现在,这就是我的库的样子(高度简化):

class GeneralMethods(object):
    def __init__(self, parent=None):
        super(GeneralMethods, self).__init__()

    def __enter__(self):
        return self

    def __exit__(self, type, value, traceback):
        return isinstance(value, TypeError)

    def say_hello(self):
        return 'hello world'

Tags: 对象内存selfhelloworldreturnobjectinit
1条回答
网友
1楼 · 发布于 2024-10-01 15:42:19

I'm a bit confused about the fact that with my code, the gm object still exists outside of the with

这是预期的行为;gm只是另一个变量,在执行离开定义它的作用域之前,它不会被垃圾收集。你知道吗

如果你确信它值得多加一行,你可以明确地这样做:

del gm

请注意,它并不保证对象会立即被垃圾收集—如果gm是对对象的唯一引用,它只会使对象在执行离开作用域之前有资格被垃圾收集。你知道吗


如果你关心的是记忆,那么看看^{}。你知道吗

相关问题 更多 >

    热门问题