An adorner (decorator) is a high-level python syntax. Adorners can process a function, method, or class. In Python, there are a number of ways to work with functions and classes, such as in a python closure, where we see function objects as the result of a function return. In contrast to other methods, the adorner has a simple syntax and high code readability. As a result, adorners are widely used in Python projects.
The adorner was first presented in Python 2.5, and it was originally used for processing functions and methods such as callable objects (callable object, which are defined as __call__ methods). In Python 2.6 and later Python versions, adorners are further used to process classes.
Decorative Functions and methods
We first define two simple mathematical functions, one for calculating the sum of squares and one for calculating the squared difference:
# get square sum
def square_sum (A, B): return
a**2 + b**2
# get square diff
def Square_diff (A, B):
ret Urn a**2-b**2
print (Square_sum (3, 4))
print (Square_diff (3, 4))
After having basic mathematical functions, we may want to add additional functionality to the function, such as printing input. We can rewrite the function to achieve this:
# modify:print Input
# get square sum
def square_sum (A, b):
print ("Intput:", A, b) return
a**2 + b**2< c13/># Get square diff
def Square_diff (A, b):
print ("Input", A, b) return
a**2-b**2
print (square_ SUM (3, 4))
print (Square_diff (3, 4))
We modified the definition of the function to add functionality to the function.
We now use adorners to implement the above modifications:
def decorator (F):
def new_f (A, b):
print ("Input", A, b) return to
F (A, B) return to
new_f
# get Square sum< c6/> @decorator
def square_sum (A, B): return
a**2 + b**2
# get square diff
@decorator
def square_ diff (A, b): return
a**2-b**2
print (Square_sum (3, 4))
print (Square_diff (3, 4))