忽略第 3 条条件可以如下:
class C(object):
pass
class Demo(object):
def __new__(cls, *args, **kwargs):
inst = object.__new__(cls, *args, **kwargs)
if not hasattr(Demo, 'c_inst'):
c_inst = C(*args, **kwargs)
Demo.c_inst = c_inst
inst.c_inst = Demo.c_inst
return inst
def __init__(self, *args, **kwargs):
pass
for i in range(5):
o = Demo()
print(o, o.c_inst)
输出:
>>> (<__main__.Demo object at 0x7f7bd9e95310>, <__main__.C object at 0x7f7bd9e95350>)
>>> (<__main__.Demo object at 0x7f7bd9e95390>, <__main__.C object at 0x7f7bd9e95350>)
>>> (<__main__.Demo object at 0x7f7bd9e95310>, <__main__.C object at 0x7f7bd9e95350>)
>>> (<__main__.Demo object at 0x7f7bd9e95390>, <__main__.C object at 0x7f7bd9e95350>)
>>> (<__main__.Demo object at 0x7f7bd9e95310>, <__main__.C object at 0x7f7bd9e95350>)