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

2019-04-26 17:41:23 +08:00
 fzzff

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

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

1393 次点击
所在节点    Python
3 条回复
vipppppp
2019-04-27 09:42:37 +08:00
最近第一次使用 tornado,这个框架基本是让使用者使用 initialize 而不是 __init__
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
2019-04-28 10:00:25 +08:00
@vipppppp 非常感谢!~

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/559023

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX