Python class decorator, use a small demo

To achieve the same function, it may take 50 lines in Java language, while it may only take 10 lines in Python. Perhaps many readers have heard of this from predecessors who have used Python before learning Python, and then started to go Learn Python.

Python is indeed concise and elegant, and many readers, including me, are fascinated by it.

Today, through a small example, I once again understand the clean way of Python:

We want to check every parameter to ensure that integer types cannot appear. Use class decorator, you can do clean, general:

import functools

classValidateParameters:
 def __init__(self, func):
  # Ensure that the function information is not changed after func is decorated
  functools.update_wrapper(self, func)
  self.func = func

 # Override this method to make the class object callable
 def __call__(self,*parameters):ifany([isinstance(item, int)for item in parameters]):
   raise TypeError("Parameter shouldn't be int!!")else:return self.func(*parameters)

Use the above class to start decorating our various functions, such as the concatenating string function concat, the first call to pass parameters are strings, and the type meets the requirements; the second call to pass parameters has an integer type, and an exception is thrown: Parameter shouldn't be int!!

@ ValidateParameters
def concat(*list_string):return"".join(list_string)

# returns anb
print(concat("a","n","b"))

# raises Error.print(concat("a",1,"c"))

Any function that wants to have type checking can be decorated with ValidateParemeters. The capital function is as follows. After the string is concatenated, the first letter should be capitalized:

@ ValidateParameters
def capital(*list_string):returnconcat(*list_string).capitalize()print(capital("a","n","b"))print(capital(2,"n","b"))

If the input parameter has an integer type, the above exception must be thrown, and type checking is again convenient.

The above uses the Python class decorator to implement a small demonstration of code clean.

Commonly used frameworks such as Pandas, TensorFlow, Keras, etc., can see similar usage in the source code. This kind of syntax makes Python truly clean.

To master Python, you need to understand from the outside to the inside. This year, I spent more than 4 months to organize 20 core Python topics, which are very suitable for beginners. Here are a few chapters:

After you have mastered and understood these 20 topics, you can read a few in-depth Python tutorials. I believe you will be an expert at that time.

Recommended Posts

Python class decorator, use a small demo
Python decorator
100 small Python examples
python-Use python to write a small shopping program
Python crawler-beautifulsoup use
Python3 external module use