我有一个 Python 3 类,它目前是使用 @singleton 装饰器定义的单例,但有时它需要不是是单例。
问题:是否可以在实例化类的对象时传递一个参数,由该参数决定该类是单例还是非单例?
我正试图找到一种替代方法来复制类并使它不是单例,但那样我们就会有大量重复的代码。
Foo.py
def singleton(cls):
instances={}
def getinstance(*args, **kwargs):
if cls not in instances:
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return getinstance
@singleton
Class Foo:
def hello(self):
print('hello world!')
FooNotSingleton.py
Class FooNotSingleton:
def hello(self):
print('hello world!')
main.py
from Foo import Foo
from FooNotSingleton import FooNotSingleton
foo = Foo()
foo.hello()
bar = FooNotSingleton()
bar.hello()
请您参考如下方法:
您可以在 singleton 包装器中使用关键字触发器添加一些额外的处理,以绕过类中使用 singleton=False 的非单一实例化:
def singleton(cls):
instances={}
def getinstance(*args, **kwargs):
# thanks to sanyash's suggestion, using a default return instead of try/except
singleton = kwargs.pop('singleton', True)
if singleton:
if cls not in instances:
instances[cls] = cls(*args, **kwargs)
return instances[cls]
else:
return cls(*args, **kwargs)
return getinstance
@singleton
class Foo:
def __init__(self, val):
self.val = val
def hello(self):
print(f'I have value {self.val}')
测试:
s1 = Foo('single')
s2 = Foo('another single')
ns = Foo('not single', singleton=False)
s1.hello()
# I have value single
s2.hello()
# I have value single
ns.hello()
# I have value not single
需要注意的是,您需要保留一个不太可能用于任何修饰类的关键字。好处是您只需创建一次类而不会重复。
