Issue
I'm looking for the right way to create a singleton class that accepts arguments in the first creation. My research lead me to 3 different ways:
Metaclass
class Singleton(type):
instance = None
def __call__(cls, *args, **kwargs):
if cls.instance is None:
cls.instance = super(Singleton, cls).__call__(*args, **kwargs)
return cls.instance
class ASingleton(metaclass=Singleton):
pass
__new__
class Singleton(object):
instance = None
def __new__(cls, *args, **kwargs):
if cls.instance is None:
cls.instance = super().__new__(cls, *args, **kwargs)
return cls.instance
Decorator
def Singleton(myClass):
instances={}
def getInstance(*args, **kwargs):
if myClass not in instances:
instances[myClass] = myClass(*args, **kwargs)
return instances[myClass]
return getInstance
@Singleton
class SingletonTest(object):
pass
All of them work fine, but when it comes to initiation (like using __init__ in normal class) I can't figure out the right way to implement it. The only solution I can think about is using the metaclass method in this way:
class Singleton(type):
instance = None
def __call__(cls, *args, **kwargs):
if cls.instance is None:
cls.instance = super(Singleton, cls).__call__(*args, **kwargs)
return cls.instance
class ASingleton(metaclass=Singleton):
def __init__(self,j):
self.j=j
I don't know if this is the correct way to create singleton that accepts arguments.
Solution
I've found out that the best way to implement Singleton is by using meta classes:
class Singleton (type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]
# Python 2
class MyClass():
__metaclass__= Singleton
# Python 3
class MyClass(metaclass=Singleton):
pass
Answered By - Andriy Ivaneyko
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.