Decorating a class-help - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Decorating a class-help (/thread-18736.html) |
Decorating a class-help - yoniker - May-29-2019 Hi! I'm not too sure why the following code is working: class Statics(): lock = threading.Lock() def thread_safe(func): def inner(*args,**kwargs): with Statics.lock: result = func(*args, **kwargs) return result return inner @thread_safe def singleton(class_): instances = {} def getinstance(*args, **kwargs): if class_ not in instances: instances[class_] = class_(*args, **kwargs) return instances[class_] return getinstanceSpecifically,the singleton decorator,which decorates a class,is working, but I don't understand why. Usually a class decorator returns another class. RE: Decorating a class-help - Gribouillis - May-29-2019 A python class is not only a class, it is also a callable that returns instances. With this decorator, after @singleton class A: passthe object named A in the current namespace is not a class. Instead it is a function that returns A instances. The code supposes that you're not interested in anything else about A. You can still writea = A()and get (the only) instance of the class. But you cannot do A.some_static_member and get the corresponding member of class A.IMHO it is a huge waste of time to spend hours on the singleton pattern in python. Python is for responsible adults, so if you want a singleton, just create a single instance. |