Python decorator

from functools import wraps

def single(cls):
    sets={}
    print(sets)
  
    @wraps(cls)
    def wrapper(*args,**kw):
        if "ex" not in sets:
            sets["ex"]=cls(*args,**kw)
        return sets["ex"]
    return wrapper

@single
class B:
    pass

b=B()
b.a="hello bachelor"
a=B()
d=single(B)
print(c.a)

Singleton pattern implemented through decorators, but there is one area that is not particularly understood:

Create two instances of B through object=B () in the

code, why

 sets={}
 print(sets)

this paragraph was executed only once.

another puzzle is

@decorator
class B:
    pass

decorator(B)

but if d=single (B) is used in the code, the sets= {} section will be executed.

Apr.03,2021

to put it simply:

The
  • print code is only called when the decorator declares class B for the first time, and removing the following code will execute
b=B()
b.a="hello bachelor"
a=B()
d=single(B)
print(c.a)
  • d=single (B) is equivalent to re-executing the single function, from top to bottom

PS: you can first use the following code to take a look at the specific execution process (enter s to step)

import pdb;pdb.set_trace()
Menu