python - 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__
它来装饰课堂更好吗?如何?
解决方案
推荐阅读
- javascript - 当我单击暗模式按钮时,我也想将暗模式应用于 iframe 标签
- powershell - Atlassian Bamboo - 注入具有“?”的变量 在字符串中,可能的编码问题
- amazon-web-services - 如何在无服务器中引用堆栈输出值?
- java - Android:链接两个视图模型的最佳方式
- php - laravel如何接受PUT请求数据?
- r - 比较 R 中的连续行,显示它们是增加还是减少
- ruby - 如何使干净的 if-else + 返回值
- c# - 对象在成为游戏对象的子对象时变形
- sql - 如何在sql中进行转换和旋转
- python-3.x - 带有标准输入和标准输出的 FizzBuzz python 代码