V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX  ›  leafcoder  ›  全部回复第 1 页 / 共 1 页
回复总数  1
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   ·   实用小工具   ·   4669 人在线   最高记录 6679   ·     Select Language
创意工作者们的社区
World is powered by solitude
VERSION: 3.9.8.5 · 9ms · UTC 09:59 · PVG 17:59 · LAX 01:59 · JFK 04:59
Developed with CodeLauncher
♥ Do have faith in what you're doing.