leafcoder 最近的时间轴更新
leafcoder

leafcoder

Life is short, use Python.
V2EX 第 528113 号会员,加入于 2021-01-13 13:45:53 +08:00
玩蛇人属蛇。
leafcoder 最近回复了
2021-03-01 10:10:38 +08:00
回复了 capbone 创建的主题 Python Python :如何避免某个函数内的类反复进行实例化?
忽略第 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>)
关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   1004 人在线   最高记录 6679   ·     Select Language
创意工作者们的社区
World is powered by solitude
VERSION: 3.9.8.5 · 94ms · UTC 22:29 · PVG 06:29 · LAX 14:29 · JFK 17:29
Developed with CodeLauncher
♥ Do have faith in what you're doing.