feather12315
V2EX  ›  问与答

Python 生成器

  •  
  •   feather12315 · Apr 3, 2016 · 1724 views
    This topic created in 3721 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
        1
    lecher  
       Apr 3, 2016   ❤️ 2
    python 有内存分析的模块: memory_profiler
    用 pip 安装之后,可以通过在方法前加 @profile 之后执行 python -m memory_profiler filename.py 检查内存情况

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