[Python] Decorator

Rex Chiang
2 min readFeb 15, 2022

--

Basic usage

def decorator(func):
print("Register The Decorator")

def inner():
print("Inner")
func()

return inner

@decorator
def function():
print("Function")

if __name__ == "__main__":
# Register The Decorator
print("Call Function") # Call Function
function() # Inner
# Function
  • Decorator would setup if python file start to compile, even if the function not be called.
  • Above code equal to decorator(function).
def decorator(func):
print("Register The Decorator")

def inner(x):
print(x + "_Inner")
func(x)

return inner

@decorator
def function(x):
print(x)

if __name__ == "__main__":
# Register The Decorator
print("Call Function") # Call Function
function("Function") # Function_Inner
# Function
  • Above code equal to decorator(function) with parameter x.

Multiple usage

def decorator1(func):
print("Register The Decorator1")

def inner1():
print("Inner1")
func()

return inner1

def decorator2(func):
print("Register The Decorator2")

def inner2():
print("Inner2")
func()

return inner2

@decorator1
@decorator2
def function():
print("Function")

if __name__ == "__main__":
# Register The Decorator2
# Register The Decorator1
print("Call Function") # Call Function
function() # Inner1
# Inner2
# Function
  • Above code equal to decorator1(decorator2(function)).

Parameter usage

def decorator_param(active = False):
print("Register The Decorator_Param")

def decorator(func):
print("Register The Decorator")

if active:
def inner():
print("Inner")
return inner
else:
return func

return decorator

@decorator_param(active = True)
def function():
print("Function")

if __name__ == "__main__":
# Register The Decorator_Param
# Register The Decorator
print("Call Function") # Call Function
function() # Inner
  • Use outside decorator to pass the parameter into inside decorator.

Class usage

class Decorator:
print("Register The Decorator")

def __init__(self, func):
self.f = func

def inner(self):
print("Inner")

@Decorator
def function():
print("Function")

if __name__ == "__main__":
# Register The Decorator
print("Call Function") # Call Function
function.f() # Function
function.inner() # Inner
  • The function will pass into the initializer in Decorator class.
  • One of the ways for encapsulation.

--

--

No responses yet