推荐学习书目
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
towry
V2EX  ›  Python

Python reload 对单例对象的影响

  •  
  •   towry · Jan 23, 2021 · 2556 views
    This topic created in 1957 days ago, the information mentioned may be changed or developed.
    假如在 python 中使用了单例模式,维护了一个变量,那么在模块被 reload 后,这个变量会变吗?
    2 replies    2021-01-24 01:56:17 +08:00
    hareandlion
        1
    hareandlion  
       Jan 23, 2021   ❤️ 1
    这要看单例模式的对象是在哪里创建的了吧,一般情况下单例模式所引用的对象是在被 reload 的 module 里初始化的,那 reload 会创建新的对象,而如果单例引用的是存在内存里类似 int 的基本类型对象,reload 之后依然会引用原本的对象。

    si_cls.py
    ```
    #!/bin/python
    # coding: utf-8

    ph = {'ab': 2}
    # ph = 32


    class SI:
    def __new__(cls, *args, **kwargs):
    return ph

    def id(self):
    return id(self)


    si_instance = SI()
    ```

    test.py
    ```
    #!/bin/python
    # coding: utf-8

    import si_cls
    from importlib import reload

    s1 = si_cls.SI()
    s2 = si_cls.SI()

    print(f'id(s1)={id(s1)}, id(s2)={id(s2)}, id(si_instance)={id(si_cls.si_instance)}')

    reload(si_cls)

    s1 = si_cls.SI()
    s2 = si_cls.SI()

    print(f'id(s1)={id(s1)}, id(s2)={id(s2)}, id(si_instance)={id(si_cls.si_instance)}')

    ```
    abersheeran
        2
    abersheeran  
       Jan 24, 2021 via Android   ❤️ 2
    巧了。以前研究过相关的东西写了一篇博客留作记录。你看看吧。https://aber.sh/articles/Python-Reload/

    当时写的可能比较乱,如果有没看懂的部分可以文章下发评论问。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1047 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 22:55 · PVG 06:55 · LAX 15:55 · JFK 18:55
    ♥ Do have faith in what you're doing.