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()
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b31bd8-2bdd2.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b31bd8-2bdd2.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?