V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
wisefree
V2EX  ›  Python

Python 内存回收机制的疑问

  •  
  •   wisefree · 2017-07-10 00:42:57 +08:00 · 2617 次点击
    这是一个创建于 2474 天前的主题,其中的信息可能已经有所发展或是发生改变。

    代码和注释如下,先谢谢各位

    # -*- coding: utf-8 -*-
    
    class A(object):
        def __init__(self, name):
            self.name = name
            
        def foo(self):
            print(self.name)
        
    all_name = ['a', 'b', 'c', 'd', 'e']  # 甚至更多
    
    for name in all_name:
        
        a = A(name)  # 得到一个实例
        a.foo()      # 这个实例在执行这个函数后,会不会被垃圾回收呢?
                     # 如果不立即回收,是不是循环多次后,内存是不是占用很大?
                     # 在循环中不断构造实例,是不是合理的?
    
    6 条回复    2017-07-10 10:08:58 +08:00
    BarrelTitor
        1
    BarrelTitor  
       2017-07-10 00:59:06 +08:00   ❤️ 1
    在 A 中加个__del__方法,print 一下应该就可以看到了。
    我 mac 上 3.6 是立刻删除的。
    est
        2
    est  
       2017-07-10 01:09:33 +08:00 via iPhone   ❤️ 1
    a 不会回收但是第二个循环重新赋值之后就回收了
    wwqgtxx
        3
    wwqgtxx  
       2017-07-10 01:43:06 +08:00 via iPhone   ❤️ 1
    @BarrelTitor 不过平时最好不要加__del__方法,否则在两个类有循环引用的情况下会无法垃圾回收
    wisefree
        4
    wisefree  
    OP
       2017-07-10 09:27:00 +08:00
    @BarrelTitor 这种在循环不断构造实例,合理就行,以前都是构造几个类就 OK 了,突然放在循环里有点不适应
    wisefree
        5
    wisefree  
    OP
       2017-07-10 09:27:18 +08:00
    @est ok,谢谢啦
    ToBeHacker
        6
    ToBeHacker  
       2017-07-10 10:08:58 +08:00
    Python 主要通过引用计数清理垃圾,在二次循环后 a 被重新复制,原先的引用减为 0 后就会被立即清理
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3653 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 04:51 · PVG 12:51 · LAX 21:51 · JFK 00:51
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.