gpt4 book ai didi

python - 为什么 python 中的 Singleton 多次调用 __init__ 以及如何避免它?

转载 作者:太空宇宙 更新时间:2023-11-03 12:46:48 24 4
gpt4 key购买 nike

我已经在 python 中实现了单例模式,但我注意到init 被无用地调用,每次我调用 MyClass,尽管返回相同的实例。

如何避免?

class Test(object):
def __init__(self, *args, **kwargs):
object.__init__(self, *args, **kwargs)

class Singleton(object):
_instance = None

def __new__(cls):
if not isinstance(cls._instance, cls):
cls._instance = object.__new__(cls)
return cls._instance

class MyClass(Singleton):
def __init__(self):
print("should be printed only 1 time")
self.x=Test()
pass

a = MyClass() # prints: "should be printed only 1 time"
b = MyClass() # prints ( again ): "should be printed only 1 time"

print(a,b) # prints: 0x7ffca6ccbcf8 0x7ffca6ccbcf8
print(a.x,b.x) # prints: 0x7ffca6ccba90 0x7ffca6ccba90

最佳答案

问题是 __new__ 不返回对象,它返回一个未初始化的对象,之后调用 __init__

你根本无法避免。您可以执行以下操作(使用元类型):

class Singleton(type):
def __init__(self, name, bases, mmbs):
super(Singleton, self).__init__(name, bases, mmbs)
self._instance = super(Singleton, self).__call__()

def __call__(self, *args, **kw):
return self._instance

class Test(metaclass = Singleton):
# __metaclass__ = Singleton # in python 2.7
def __init__(self, *args, **kw):
print("Only ever called once")

关于python - 为什么 python 中的 Singleton 多次调用 __init__ 以及如何避免它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31269974/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com