开发者

Python implementation of Singleton

开发者 https://www.devze.com 2023-04-05 19:49 出处:网络
code goes first: def singleton(cls): instances = {} def get_instance(): if cls not in instances: instances[cls] = cls()

code goes first:

def singleton(cls):
    instances = {}
    def get_instance():
        if cls not in instances:
            instances[cls] = cls()
        return inst开发者_Go百科ances[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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号