feather12315
V2EX  ›  问与答

Python 生成器

  •  
  •   feather12315 · Apr 3, 2016 · 2025 views
    This topic created in 3889 days ago, the information mentioned may be changed or developed.

    对生成器不算了解,只是会用。可现在遇到了一个问题:

    def test():
        a = 1
        b = 2
        c = 3
        while True:
            yield c
            c += 1
    

    执行这段代码, a, b 变量还占用空间吗?

    若占用的话,有啥办法可以实现相同的功能而避免 a b 变量占用空间呢?

    实际情况是内存有点小, yield 的是一个回调函数,不想办法压榨内存的话会溢出。。。

    5 replies  •  2016-04-05 12:27:04 +08:00
    lecher
    lecher
    Apr 3, 2016❤️2
    1
    python 有内存分析的模块: memory_profiler
    用 pip 安装之后,可以通过在方法前加 @profile 之后执行 python -m memory_profiler filename.py 检查内存情况

    代码和变量都会占用内存,生成器在引用之后,只要引用数大于 0 ,是不会释放里面声明的内容的。
    feather12315
    feather12315
    OP
    Apr 3, 2016
    2
    @lecher Thanks. 我看看这
    julyclyde
    julyclyde
    Apr 5, 2016
    3
    @lecher 试了试,貌似对 generator 函数, memory_profiler 无效。不知道原理
    julyclyde
    julyclyde
    Apr 5, 2016❤️1
    4
    我猜可能是因为 generator 函数没有 return , decorator 不知道它什么时候完成的
    feather12315
    feather12315
    OP
    Apr 5, 2016 via Android
    5
    @julyclyde 唔。最近有些忙,我还没看。。谢谢你啦。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   4019 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 23ms · UTC 01:07 · PVG 09:07 · LAX 17:07 · JFK 20:07
    ♥ Do have faith in what you're doing.