Methods in the Python decorator decoration class

Source: Internet
Author: User
Tags throw exception python decorator

Most of the tutorials currently available on the Chinese web for decorators are about decorating a common function. This article describes how to use the Python adorner to decorate a class method, while invoking other methods within the class in the adorner function. This article describes an exception that captures a method as an example.

There is a class test, which has the following structure:

There is a method in the class where read_value() this method is called in multiple places. For some reason, the method read_value may randomly throw exception causing the program to crash. So the whole method needs to be try ... except dealt with. The ugliest thing to do is as shown in the following code:

This can solve the problem, but the code is not pythonic.

Using adorners to solve this problem, should the adorner function be written inside the class or outside the class? The answer is, write outside the class. So how do you invoke other methods of this class, since it's written outside of the class?

First, write an adorner that handles the most common exceptions:

This notation can actually catch origin_func() the exception, but what if, in the event of an exception, you need to invoke another method inside the class to handle the exception? The answer is to add a parameter to wrapper: self.

You only need to modify the part of the adorner definition , where the adorner is used without modification at all.

By adding a self parameter, the adorner outside the class can directly use the various methods within the class, or you can use the properties of the class directly. The above is a simple case of external function decoration class inside method

Methods in the Python decorator decoration class

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.