推荐学习书目
› 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 · Sep 3, 2021 · 2407 views
    This topic created in 1887 days ago, the information mentioned may be changed or developed.

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

    12 replies  •  2021-09-09 09:27:14 +08:00
    deplivesb
    deplivesb
    Sep 3, 2021
    1
    python 有析构函数??
    LoNeFong
    LoNeFong
    Sep 3, 2021
    2
    @zhangdeplives 应该说的是__del__
    frostming
    frostming
    Sep 3, 2021
    3
    1L 的目的是提醒 __del__ 不能叫做析构函数,如果按照析构函数去理解__del__的作用那多半是会出现大的偏差
    lucays
    lucays
    Sep 3, 2021 via Android
    4
    什么场景需要自己去实现 del 。。。感觉是其他语言的思维带过来了吧
    learningman
    learningman
    Sep 3, 2021 via Android
    5
    我写 py 还没用过 del
    renmu123
    renmu123
    Sep 3, 2021 via Android
    6
    Python 一般用 with 来实现
    deplivesb
    deplivesb
    Sep 3, 2021
    7
    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
    princelai
    Sep 4, 2021 via Android
    8
    我之前发帖问过双下划线 del,用于析析构,问题很大,不如去了解下 weakref,可能符合你要求
    paniford
    paniford
    OP
    Sep 9, 2021
    9
    @princelai 好的谢谢
    paniford
    paniford
    OP
    Sep 9, 2021
    10
    @lucays 提供给用户的代码编辑器,可能需要手动释放 gpu 或者一些资源的场景
    paniford
    paniford
    OP
    Sep 9, 2021
    11
    @zhangdeplives 明白了,谢谢,我下次看文档
    paniford
    paniford
    OP
    Sep 9, 2021
    12
    就怕如果 del 的时候出错,gpu 没被释放的话,要不要考虑后端处理一下
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1315 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 35ms · UTC 20:39 · PVG 04:39 · LAX 12:39 · JFK 15:39
    ♥ Do have faith in what you're doing.