mardi 9 novembre 2021

Singleton that instantiates a class by its object and arguments

I'm trying to prepare a singleton class that would distinguish the instances not only by class types, but also by arguments with which the class was called.

Let's say I've a Singleton class like below:

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]

And now I'm trying to create two class instances with different parameters:

class MyClass(metaclass=Singleton):
    def __init__(self, x, y):
        print(f"Called constructor with x as {x} and y as {y}")

a = MyClass(1, 2)
b = MyClass(1, 2)
print(id(a) == id(b))  # Returns True, which is fine


c = MyClass(1, 3)
d = MyClass(1, 2)
print(id(c) == id(d))  # Returns True, which is not really fine to me :)
                       # Moreover y in that case is 3, not 2.

What in case I want to distinguish instances in singleton additionally by parameters with which the class was initialized?

Aucun commentaire:

Enregistrer un commentaire