【发布时间】:2019-10-08 13:48:23
【问题描述】:
我有一个 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()
【问题讨论】:
-
1.
_singleton未定义。你的意思是getinstance?。 2. 愚蠢的问题:为什么不直接删除@singleton装饰器? -
@sanyash 1. 修正错字,谢谢! 2.我希望同一个类有单例和非单例版本,所以单例版本的类应该有
@singleton装饰器,非单例版本不应该。也许我错过了一些非常明显的东西? -
您介意接受一个给定的答案吗?
标签: python python-3.x singleton