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
paniford
V2EX  ›  Python

Python 类的析构函数的一些疑问,析构到底是和类绑定一起释放还是类释放以后调用的函数。

  •  1
     
  •   paniford · 2021-09-03 11:25:58 +08:00 · 1368 次点击
    这是一个创建于 937 天前的主题,其中的信息可能已经有所发展或是发生改变。

    在对 python 实现代码拼接的时候将用户的代码拼接成一个类,其中析构函数可能会用来释放一些资源,不确定如果析构函数在调用的时候出错的话,资源会不会被释放。我也手动调用了 gc,这个过程中,看了网上一些说明,没搞明白析构函数是释放完类以后调用了析构函数还是调用完析构释放了整个包含析构的类?

    12 条回复    2021-09-09 09:27:14 +08:00
    deplivesb
        1
    deplivesb  
       2021-09-03 13:18:28 +08:00
    python 有析构函数??
    LoNeFong
        2
    LoNeFong  
       2021-09-03 14:21:31 +08:00
    @zhangdeplives 应该说的是__del__
    frostming
        3
    frostming  
       2021-09-03 14:24:23 +08:00
    1L 的目的是提醒 __del__ 不能叫做析构函数,如果按照析构函数去理解__del__的作用那多半是会出现大的偏差
    lucays
        4
    lucays  
       2021-09-03 14:42:49 +08:00 via Android
    什么场景需要自己去实现 del 。。。感觉是其他语言的思维带过来了吧
    learningman
        5
    learningman  
       2021-09-03 16:31:05 +08:00 via Android
    我写 py 还没用过 del
    renmu123
        6
    renmu123  
       2021-09-03 16:33:38 +08:00 via Android
    Python 一般用 with 来实现
    deplivesb
        7
    deplivesb  
       2021-09-03 16:56:57 +08:00
    Note del x doesn’t directly call x.__del__() — the former decrements the reference count for x by one, and the latter is only called when x’s reference count reaches zero.

    上面这句话摘自 python 3.9.7 doc 对__del__的注释

    如果你真的需要手动的去释放某些""
    princelai
        8
    princelai  
       2021-09-04 12:18:45 +08:00 via Android
    我之前发帖问过双下划线 del,用于析析构,问题很大,不如去了解下 weakref,可能符合你要求
    paniford
        9
    paniford  
    OP
       2021-09-09 09:18:56 +08:00
    @princelai 好的谢谢
    paniford
        10
    paniford  
    OP
       2021-09-09 09:20:46 +08:00
    @lucays 提供给用户的代码编辑器,可能需要手动释放 gpu 或者一些资源的场景
    paniford
        11
    paniford  
    OP
       2021-09-09 09:21:43 +08:00
    @zhangdeplives 明白了,谢谢,我下次看文档
    paniford
        12
    paniford  
    OP
       2021-09-09 09:27:14 +08:00
    就怕如果 del 的时候出错,gpu 没被释放的话,要不要考虑后端处理一下
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3013 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 15:03 · PVG 23:03 · LAX 08:03 · JFK 11:03
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.