How does python define the decorator with parameters and python parameters?
The example in this article shares with you the code for defining a parameter-based modifier in python for your reference. The specific content is as follows:
Case:
Implement a decorator to check the parameter type of the decorator function.
Requirements:
The decorator can specify the function parameter type through a function. When a function is called, an exception is thrown when a parameter is passed in and no matching is detected.
How can this problem be solved?
First, you need to obtain the function signature, and obtain the parameters in the decorator. Then, bind the function signature to the parameters in the decorator.
Bind the parameters passed in when calling the function with the function signature.
Compare the data types defined in the real parameters with the data defined in the decorator. If the data type does not match, an exception is thrown.
#! /Usr/bin/python3 from inspect import signature def check_type (* ty_args, ** ty_kwargs): def out_wrapper (func): # obtain the function parameters by using the signature method: name, age, height sig = signature (func) # obtain the parameters sent from the decorator. The function signature is bound to it. The dictionary type is bind_types = sig. bind_partial (* ty_args, ** ty_kwargs ). arguments print (bind_types) def wrapper (* args, ** kwargs): # bind the real parameters in the execution function to the form of a dictionary. func_type = sig. bind (* args, ** kwargs ). arguments. items () print (func_type) # The items () form of cyclic parameters and real-name dictionary for name, obj in func_type: if name in bind_types: if not isinstance (obj, bind_types [name]): raise TypeError ('% s must be % s' % (name, bind_types [name]) func (* args, ** kwargs) return wrapper return out_wrapper # type check @ check_type (str, int, float) def func (name, age, height): print (name, age, age, height) if _ name _ = '_ main _': func ('bei _ men', 18, 1.75)
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.