我有一个 Python 3 类,目前是使用 a 定义的单例@singleton
装饰器,但有时需要not成为单身人士。
问题:是否可以在从类实例化对象时执行类似于传递参数的操作,并且该参数确定该类是否是单例?
我试图找到一种替代方法来复制类并使其不是单例,但这样我们就会有大量重复的代码。
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}')
Test:
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
需要注意的是,您需要保留一个不太可能在任何装饰类中使用的关键字。好处是您只需创建该类一次,无需重复。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)