Reputation: 18625
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?
Upvotes: 0
Views: 451
Reputation: 45089
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.
Upvotes: 1
Reputation: 176980
When you call MyClass()
after it's been decorated, you're right -- you're not actually calling a class, you're calling a function.
That function calls the class if cls not in instances
and caches it, then returns the cached instance.
In other words, there is no reason MyClass()
has to call the class directly -- it will work as expected as long as it returns an instance of the class.
Upvotes: 1