gpt4 book ai didi

python - 使 isinstance(obj, cls) 与装饰类一起工作

转载 作者:太空狗 更新时间:2023-10-30 02:30:28 24 4
gpt4 key购买 nike

我有几个类需要执行以下操作:

调用构造函数时,如果已经存在一个相等的对象(也就是具有相同 id 的对象),则返回该对象。否则,创建一个新实例。基本上,

>>> cls(id=1) is cls(id=1)
True

为了实现这一点,我编写了一个类装饰器,如下所示:

class Singleton(object):
def __init__(self, cls):
self.__dict__.update({'instances': {},
'cls': cls})

def __call__(self, id, *args, **kwargs):
try:
return self.instances[id]
except KeyError:
instance= self.cls(id, *args, **kwargs)
self.instances[id]= instance
return instance

def __getattr__(self, attr):
return getattr(self.cls, attr)
def __setattr__(self, attr, value):
setattr(self.cls, attr, value)

这就是我想要的,但是:

@Singleton
class c(object):
def __init__(self, id):
self.id= id

o= c(1)
isinstance(o, c) # returns False

我该如何解决这个问题?我找到了一个 related question ,但我似乎无法使这些解决方案适应我的用例。


我知道有人会要求我发布一些不起作用的代码,所以在这里:

def Singleton(cls):
instances= {}
class single(cls):
def __new__(self, id, *args, **kwargs):
try:
return instances[id]
except KeyError:
instance= cls(id, *args, **kwargs)
instances[id]= instance
return instance
return single
# problem: isinstance(c(1), c) -> False

def Singleton(cls):
instances= {}
def call(id, *args, **kwargs):
try:
return instances[id]
except KeyError:
instance= cls(id, *args, **kwargs)
instances[id]= instance
return instance
return call
# problem: isinstance(c(1), c) -> TypeError

最佳答案

您可以添加自定义 __instancecheck__ Hook 你的装饰类:

def __instancecheck__(self, other):
return isinstance(other, self.cls)

关于python - 使 isinstance(obj, cls) 与装饰类一起工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26682710/

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