SoFunction
Updated on 2024-11-17

Python Decorator Characterization Principles Explained

This article introduces the characteristics of python decorator principle explained, the text of the sample code through the introduction of the very detailed, for everyone's learning or work has a certain reference learning value, you can refer to the following friends

Today I discovered another use for decorators, so here's the code first:.

data_list = []
def data_item(func):
  data_list.append(func)
  return func
@data_item
def foo():
  return 1
@data_item
def foo1():
  return 2
@data_item
def foo3():
  return 3
def max_item():
  result = max(i() for i in data_list)
  return result
if __name__ == '__main__':
  item = max_item()
  print(item)

code is very simple is that, the definition of three foo function at the beginning of each foo function output is not the same as the number of decorator data_item modifier, and finally through the max_item function, the implementation of a series of logic to obtain the results.

An easy point to miss here is that the decorator is actually executed before max_item() is executed.
So, if you print the data_list you will see that it has values.

[<function foo at 0x10bb05ea0>, <function foo1 at 0x10bb05d90>, <function foo3 at 0x10bb05f28>]

I.e., there are already three functions modified by the decorator in the list, and then in the

max(i() for i in data_list)

In the i() stage these three functions are executed and the result (1,2,3) is obtained and then finally their max value i.e. 3 is taken.

What scenarios will be used, generally for passing a value and then a variety of processing options, choose the best among them when you can consider using this method.
emmm, decorators are still fun.

This is the whole content of this article, I hope it will help you to learn more.