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