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

Python reload 对单例对象的影响

  •  
  •   towry · 2021-01-23 17:23:30 +08:00 · 1891 次点击
    这是一个创建于 1187 天前的主题,其中的信息可能已经有所发展或是发生改变。
    假如在 python 中使用了单例模式,维护了一个变量,那么在模块被 reload 后,这个变量会变吗?
    2 条回复    2021-01-24 01:56:17 +08:00
    hareandlion
        1
    hareandlion  
       2021-01-23 21:54:42 +08:00   ❤️ 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  
       2021-01-24 01:56:17 +08:00 via Android   ❤️ 2
    巧了。以前研究过相关的东西写了一篇博客留作记录。你看看吧。https://aber.sh/articles/Python-Reload/

    当时写的可能比较乱,如果有没看懂的部分可以文章下发评论问。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5242 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 08:18 · PVG 16:18 · LAX 01:18 · JFK 04:18
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.