code goes first:
def singleton(cls):
instances = {}
def get_instance():
if cls not in instances:
instances[cls] = cls()
return instances[cls]
return get_instance
@singleton
class A:
#...
Ok, the code above is an implementation of Singleton, I saw this implementation in another post.
I don’t understand why the singleton function returns a function but A is a class.
How does it worK?
A isn’t a class in the end. The class A gets created, but then replaced with the function that singleton returns. So in the end, A ends up being a function.
But since you call a class to create a object, it ends up working pretty much the same way. But isinstance won’t work.
P.S. you probably shouldn’t use a singleton. In python it is almost always the wrong choice.