0

I have the following Python code:

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):
    def __init__(self, i, j):
        self.i = i
        self.j = j
      
    def out(self):
        print(i)
        print(j)
  
    def __call__(self,i,j) :
    print("call_SingletonClass")
    self.i=i
    self.j=j


x = SingletonClass(1,2)
y = SingletonClass(1,3)
print(x == y)

when i am calling x = SingletonClass(1,3) what exactly happens ? and how the __call__ function is triggered from the Singleton class and the call_ method not triggered from the SingletonClass Class ?

dave
  • 867
  • 1
  • 5
  • 11
  • 1
    Why did you use `i` and `j` in `out` method ? you can't access them. They are local variables to init – S.B Jan 17 '22 at 18:56
  • From what I can tell, you don't understand metaclasses, so I closed your question under one about that. If you meant to ask a more specific question, please [edit] to clarify and LMK. For tips, see [ask]. – wjandrea Jan 17 '22 at 18:58

1 Answers1

2

Because SingletonClass is an instance of Singleton. Like any other object, if you do my_object() it will use the __call__ method of that type.

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
  • and if i defined a call method like this under the SingletonClass def __call__(self,i,j) : print("call_SingletonClass") self.i=i self.j=j -->why this not triggered but the Singleton __call__ triggered – dave Jan 17 '22 at 19:04
  • 1
    @dave ... The *instances* of `SingletonClass` would be callable. That wouldn't affect the class itself, but instances of that class. – juanpa.arrivillaga Jan 17 '22 at 19:05
  • @dave just forget metaclsses for a second, create a class with a `__call__` method, e.g. `class Foo`, then do `instane_of_foo = Foo()`, then *call the instance*, using `instance_of_foo()` – juanpa.arrivillaga Jan 17 '22 at 19:07
  • @dave If you have a metaclass with `__call__` in it, and you implement `__call__` in your class as well, and you do `your_class()()` both of the `__call__`s would be called. The `__call__` in the metaclass is for the first parenthesis, the `__call__` the class itself is for the second parenthesis. – S.B Jan 17 '22 at 19:10