Python Adorner advanced usage

Source: Internet
Author: User

Tag: Val requires code __init__ range to implement SEL by accepting

1. Decoration type

The following is a direct look at how the code implements the adornment class:

defDecorator (aclass):classNewclass:def __init__(self, Age): Self.total_display=0 self.wrapped=AClass (age)defdisplay (self): Self.total_display+ = 1Print("Total Display", Self.total_display) self.wrapped.display ()returnNewclass@decorator # Accept a class parameterclassBird:def __init__(self, Age): Self.age= Agedefdisplay (self):Print("My Age is", self.age) Eaglelord= Bird (5) forIinchRange (3): Eaglelord.display ()

In decorator, we return a new class Newclass. In the new class, we recorded the original class-generated object (self.wrapped) and appended a new property total_display to record the number of times the display was called. We also changed the display method at the same time.

By modification, our bird class can show the number of times the display was called.

2. Adorner catch exception

There is a check class, which has the method Read_value (). For some reason, the method Read_value may throw an exception and cause the program to crash, so the entire method needs to be try....except, such as:

Before catching an exception:

classCheck (object):def __init__(self):Pass    defreceive (self):Print('receive from exception.')    defRead_value (self):Print('Here I'll do something')        'a'+ 1 # This is going to be an exception.C=check () c.read_value ()

After adding a try....except catch exception:

classCheck (object):def __init__(self):Pass    defreceive (self):Print('receive from exception.')    defRead_value (self):Try:            Print('Here I'll do something')            'a'+ 1exceptException as E:Print(e) C=check () c.read_value ()

Although the program will not report the exception, but this processing, some ugly. Take a look at how the adorner is handled:

defCatch_exception (func):defWrapper (*args,**Kwargs):Try: U= Func (*args,**Kwargs)returnuexceptException:return 'An exception raised'    returnwrapperclassCheck (object):def __init__(self):Pass    defreceive (self):Print('receive from exception.') @catch_exceptiondefRead_value (self):Print('Here I'll do something')        'a'+ 1C=check () c.read_value ()

Well, using adorners to decorate functions, this makes our code even more pythonic. But what if the program reports an exception and calls another method in the class? Very simple, add a parameter to the decorator self:

defCatch_exception (func):defWrapper (self,*args,**Kwargs):Try: U= Func (self,*args,**Kwargs)returnuexceptException:self.receive ()return 'An exception raised'    returnwrapperclassCheck (object):def __init__(self):Pass        defreceive (self):Print('receive from exception.') @catch_exceptiondefRead_value (self):Print('Here I'll do something')        'a'+ 1C=check () c.read_value ()

There is a feeling of wood, very magical.

Python Adorner advanced usage

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.