I want to implement a singleton pattern in python, and I liked the pattern described in the http://www.python-course.eu/python3_metaclasses.php.
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]
class SingletonClass(metaclass=Singleton):
pass
class RegularClass():
pass
x = SingletonClass()
y = SingletonClass()
print(x == y)
x = RegularClass()
y = RegularClass()
print(x == y)
And the code works perfect. But, the __call__()
does not have the self
, and it also does not have @classmethod
or @staticmethod
declaration.
But, in the Python data model https://docs.python.org/3/reference/datamodel.html#object.__call__ the __call__()
method has a self in the arguments.
The code does not work if I pass self
, or declare as @staticmethod
or @classmethod
.
Can someone please explain the logic of the syntax behind the __call__()
method.
cls
toself
(everywhere in the function, not just the parameter), the code would continue to work. Hell, rename it togabbledygook
and it'll work. – Jassy