我有几个课程需要执行以下操作:
当调用构造函数时,如果已存在相等的对象(也称为具有相同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
答案 0 :(得分:5)
您可以在装饰器类中添加自定义__instancecheck__
挂钩:
def __instancecheck__(self, other):
return isinstance(other, self.cls)
答案 1 :(得分:1)
作为使用装饰器制作单例类的替代解决方案,您可以改为使用元类来创建类。元类可以用于向类添加功能,就像子类可以从其超类中获取功能一样。元类的优点是名称c
实际上将直接引用类c
而不是Singleton
对象或包含对c
的构造函数的调用的函数。
例如:
class SingletonMeta(type):
"""SingletonMeta is a class factory that adds singleton functionality to a
class. In the following functions `cls' is the actual class, not
SingletonMeta."""
def __call__(cls, id, *args, **kwargs):
"""Try getting a preexisting instance or create a new one"""
return cls._instances.get(id) or cls._new_instance(id, args, kwargs)
def _new_instance(cls, id, args, kwargs):
obj = super(SingletonMeta, cls).__call__(*args, **kwargs)
assert not hasattr(obj, "id"), "{} should not use 'id' as it is " \
"reserved for use by Singletons".format(cls.__name__)
obj.id = id
cls._instances[id] = obj
return obj
def __init__(cls, classname, bases, attributes):
"""Used to initialise `_instances' on singleton class"""
super(SingletonMeta, cls).__init__(classname, bases, attributes)
cls._instances = {}
你这样使用它:
# python 2.x
class MySingleton(object):
__metaclass__ = SingletonMeta
# python 3.x
class MySingleton(object, metaclass=SingletonMeta):
pass
与装饰者的比较用法:
class IDObject(object):
def __str__(self):
return "{}(id={})".format(type(self).__name__, self.id)
@Singleton
class A(IDObject):
def __init__(self, id):
self.id = id
class B(IDObject, metaclass=SingletonMeta):
pass
format_str = """{4} class is {0}
an instance: {1}
{1} is {1} = {2}
isinstance({1}, {0.__name__}) = {3}"""
print(format_str.format(A, A(1), A(1) is A(1), isinstance(A(1), A), "decorator"))
print()
print(format_str.format(B, B(1), B(1) is B(1), isinstance(B(1), B), "metaclass"))
输出:
decorator class is <__main__.Singleton object at 0x7f2d2dbffb90>
an instance: A(id=1)
A(id=1) is A(id=1) = True
isinstance(A(id=1), A) = False
metaclass class is <class '__main__.B'>
an instance: B(id=1)
B(id=1) is B(id=1) = True
isinstance(B(id=1), B) = True