I happened to read the following code yesterday (I cannot guarantee this is a valid code):
def singleton(cls, *args, **kw):
instances = {}
def getinstance():
if cls not in instances:
instances[cls] = cls(*args, **kw)
return instances[cls]
return getinstance
@singleton
class MyClass:
...
Looks like a function singleton
is designed to decorate a class MyClass
. I understand the simple and standard decorator which, as a function, decorates a function. Like this:
def bold(func):
def wrapper():
return '<b>'+func()+'</b>'
return wrapper
@bold
def test():
return 'This is a test'
But I can't really get how the function-decorates-class thing works. Can anyone provide a more detailed example?