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

请问 tornado 框架中 Configurable 及其子类为什么要用 initialize 代替__init__

  •  
  •   fzzff · 2019-04-26 17:41:23 +08:00 · 1370 次点击
    这是一个创建于 1798 天前的主题,其中的信息可能已经有所发展或是发生改变。

    源码中 有注释: initialize vs init chosen for compatibility with AsyncHTTPClient singleton magic. If we get rid of that we can switch to init here too.

    看了下 AsyncHTTPClient 但是我还是不太明白

    3 条回复    2019-04-28 10:00:25 +08:00
    vipppppp
        1
    vipppppp  
       2019-04-27 09:42:37 +08:00
    最近第一次使用 tornado,这个框架基本是让使用者使用 initialize 而不是 __init__
    vipppppp
        2
    vipppppp  
       2019-04-27 09:50:07 +08:00
    最近第一次使用 tornado,这个框架基本是让使用者使用 initialize 而不是 __init__ ,我也很疑惑。
    刚刚回过头看 Configurable 都源码,
    发现有意思的是 initialize 是在__new__中调用的,而我们知道的是__init__是在__new__返回才调用的。
    那么结合它的注释,这个差别在与单例模式是十分有区别的。
    如果在单例模式中,__init__还是会被调用,如果在__init__进行了初始化工作,那么全局的实例(其实都是一个对象),属性都会被重置。而如果在 initialize 中,我们可以只在第一个实例化都时候进行初始化工作。

    简单都模拟一下:

    class Singleton:
    _instance = None

    def __new__(cls, *args, **kwargs):

    if cls._instance is None:
    cls._instance = super(Singleton, cls).__new__(cls)
    cls._instance.initialize()
    return cls._instance

    def initialize(self):
    self.age = 18


    class Test(Singleton):

    def __init__(self):
    self.name = 'test'


    t1 = Test()
    t1.name = 'test1'
    t1.age = 19
    print(t1.name, t1.age) # test1, 19
    t2 = Test()

    print(t1.name, t1.age) # test, 19
    print(t2.name, t1.age) # test, 19

    仅仅是个人看法,如果错误,欢迎纠正,小白一枚。。。
    其他区别我也看不出。
    fzzff
        3
    fzzff  
    OP
       2019-04-28 10:00:25 +08:00
    @vipppppp 非常感谢!~
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5607 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 06:32 · PVG 14:32 · LAX 23:32 · JFK 02:32
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.