首页 > 解决方案 > Just Once 类实例化、Singletone、@cache、@memoize、__new__,导致 sameInstance——我们当前的最佳实践应该是什么?

问题描述

我一直在尝试找出设计模式的最佳当前实践,我们希望为给定的特定参数集实例化一个类一次。

环顾四周,我看到了涉及__new__@memoize 等的解决方案。

我得出的结论是,创建一个用@functools.cache 装饰的外部函数(比如“ sameInstance ”)是最干净的方法。整个事情归结为:

@functools.cache
def sameInstance(Cls, *args, **kwArgs,):
    return Cls(*args, **kwArgs)

这是我用来测试它的一个最小但完整的示例。

import functools

@functools.cache
def sameInstance(Cls, *args, **kwArgs,):
    return Cls(*args, **kwArgs)

class ClsA(object):
    def __init__(self, oneArg, kwArgOne=None):
        self.oneArg = oneArg
        self.kwArgOne = kwArgOne

first_aInst = sameInstance(ClsA, 'arg1',)
second_aInst = sameInstance(ClsA, 'arg1',)
first_other_aInst = sameInstance(ClsA, 'argA',)
third_aInst = sameInstance(ClsA, 'arg1',)
second_other_aInst = sameInstance(ClsA, 'argA',)
first_otherKw_aInst = sameInstance(ClsA, 'argA', kwArgOne='kwA')
second_otherKw_aInst = sameInstance(ClsA, 'argA', kwArgOne='kwA')

print(f"{first_aInst}\n{second_aInst}\n{first_other_aInst}\n{third_aInst}\n{second_other_aInst}\n{first_otherKw_aInst}\n{second_otherKw_aInst}")
print(f"{third_aInst.oneArg} -- {third_aInst.kwArgOne}")
print(f"{second_other_aInst.oneArg} -- {second_other_aInst.kwArgOne}")
print(f"{first_otherKw_aInst.oneArg} -- {first_otherKw_aInst.kwArgOne}")

class SingleA(object):
    def __init__(self,):
        self.param = 'initVal'

singeltonExA = sameInstance(SingleA)
singeltonExB = sameInstance(SingleA)
singeltonExA.param = 'a-editVal'
print(f"{singeltonExB.param}")

这会产生类似:

<__main__.ClsA object at 0x7f8f6c2a85b0>
<__main__.ClsA object at 0x7f8f6c2a85b0>
<__main__.ClsA object at 0x7f8f6c2a88e0>
<__main__.ClsA object at 0x7f8f6c2a85b0>
<__main__.ClsA object at 0x7f8f6c2a88e0>
<__main__.ClsA object at 0x7f8f6c2a8250>
<__main__.ClsA object at 0x7f8f6c2a8250>
arg1 -- None
argA -- None
argA -- kwA
a-editVal

这是正确的事情。

这是否应该被视为解决此设计模式的最佳当前实践?

__new__它来装饰课堂更好吗?如何?

标签: pythonpython-3.xdecorator

解决方案


推荐阅读