Systematic learning of Python - Decorators: Basic knowledge - [Decorator parameters]

Category Catalog: General Catalog of "Systematic Learning Python"


Both function decorators and class decorators appear to accept parameters, but in fact these parameters are passed to a callable object that returns the decorator, which in turn returns a callable object. Essentially, this typically establishes multiple layers of state retention. For example, the following code:

@decorator(A, B)
def F(arg):
	pass

F(0)

Automatically maps to the following equivalent form, where the decorator is a callable object that returns the actual decorator. The returned decorator in turn returns the callable object, which is then run to call the original function name:

def decorator(A, B)
	# 保存或者使用A, B
	def actual_decorator(F):
		# 保存或者使用F
		return callable
	return actual_decorator

The outer function in this structure usually stores the decorator parameters and state information separately for use in the actual decorator, the callable it returns, or both. This code saves the state information parameters in the enclosing function scope reference, but usually you can also use class attributes to save it.

In other words, decorator parameters often mean three levels of callable objects: a callable that accepts decorator parameters, which returns a callable object to serve as a decorator, and the decorator returns a callable object to handle the The initial function or class call. Each of these three levels may be a number or class, and may hold state in the form of scope or class attributes.

Decorator parameters can be used to provide values ​​for property initialization, call tracking information tags, provide property names to be validated, etc. - any kind of configuration parameter for the object or its proxy is an alternative.

References:
[1] Mark Lutz. Python Learning Manual[M]. Machinery Industry Press, 2018.

Guess you like

Origin blog.csdn.net/hy592070616/article/details/135208069