gpt4 book ai didi

python - deepcopy 不尊重元类

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

我有一个类,根据设计,它必须遵循单例 模式。所以我继续使用 元类 实现它。一切都很好,直到报告了一个错误,总而言之,该错误说 deepcopy-ied 实例的我的 singleton 类不是相同的实例。

我可以通过继承 singleton 基类来绕过这个错误,但我宁愿不这样做,原因在 this question 中指出。 .

此问题的工作示例如下所示:

class SingletonMeta(type):
def __init__(cls, name, bases, dict):
super(SingletonMeta, cls).__init__(name, bases, dict)
cls.instance = None
def __call__(cls,*args,**kw):
print "SingletonMeta __call__ was called"
if cls.instance is None:
cls.instance = super(SingletonMeta, cls).__call__(*args, **kw)
return cls.instance

class MyClass1(object):
__metaclass__ = SingletonMeta

class SingletonBase(object):
_instance = None
def __new__(class_, *args, **kwargs):
print "SingletonBase __new__ was called"
if not isinstance(class_._instance, class_):
class_._instance = object.__new__(class_, *args, **kwargs)
return class_._instance

class MyClass2(SingletonBase):
pass

from copy import deepcopy as dcp

mm1 = MyClass1()
mm2 = dcp(mm1)
print "mm1 is mm2:", mm1 is mm2

mb1 = MyClass2()
mb2 = dcp(mb1)
print "mb1 is mb2:", mb1 is mb2

输出:

SingletonMeta __call__ was called
mm1 is mm2: False
SingletonBase __new__ was called
SingletonBase __new__ was called
mb1 is mb2: True

你能给我一些关于如何解决这个问题的建议吗?我正在运行 Python 2.7.X

最佳答案

copy 模块上的文档是这样说的:

In order for a class to define its own copy implementation, it can define special methods __copy__() and __deepcopy__(). [...] The latter is called to implement the deep copy operation; it is passed one argument, the memo dictionary. [...]

因此,如果您将这些声明为返回 self,那应该可以解决问题。

关于python - deepcopy 不尊重元类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9887501/

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