SoFunction
Updated on 2024-10-29

Explaining the use of @ in python in detail

Usage of @ in python

@ is a decorator that targets functions and acts as a call-passing parameter.
There is a difference between modifying and being modified, the‘@function'Acts as a decorator to modify the function immediately following it (either another decorator or a function definition).

Code 1

def funA(desA):
 print("It's funA")

def funB(desB):
 print("It's funB")

@funA
def funC():
 print("It's funC")

Outcome 1

It's funA

Analysis 1

@funA modifier function definition def funC() assigns funC() to the formal parameter of funA().
Execution is top-down, defining funA, funB, and then running funA(funC()).
At this point desA=funC() and then funA() outputs 'It's funA'.

Code 2

def funA(desA):
 print("It's funA")

def funB(desB):
 print("It's funB")

@funB
@funA
def funC():
 print("It's funC")

Outcome 2

It's funA
It's funB

Analysis 2

@funB modifies the decorator @funA, @funA modifies the function definition def funC(), assigns funC() to the formal parameter of funA(), and assigns funA(funC()) to funB().
Execution is top-down, defining funA, funB, and then running funB(funA(funC())).
At this point desA=funC(), then funA() outputs 'It's funA'; desB=funA(funC()), then funB() outputs 'It's funB'.

Code 3

def funA(desA):
 print("It's funA")

 print('---')
 print(desA)
 desA()
 print('---')

def funB(desB):
 print("It's funB")

@funB
@funA
def funC():
 print("It's funC")

Outcome 3

It's funA
< function funC at 0x000001A5FF763C80 >
It's funC
It's funB

Analysis 3

Ditto, for a more intuitive look at parameter passing, print desA, which is passed the address of funC(), i.e., desA is now the function desA().
Executing desA() means executing funC(), desA=desA()=funC().

Code 4

def funA(desA):
 print("It's funA")

def funB(desB):
 print("It's funB")
 print('---')
 print(desB)

@funB
@funA
def funC():
 print("It's funC")

Outcome 4

It's funA
It's funB
None

Analysis 4

The above passes funC() as a parameter to funA, so how does funA(funC()) pass to funB()? Printing desB reveals that no parameters are passed.
Is it possible to understand that when 'decorator' modifies 'decorator', only the function is called.

The above is a small introduction to the use of @ in python detailed integration, I hope to help you, if you have any questions please leave me a message, I will promptly reply to you. Here also thank you very much for your support of my website!