When you look at the Python Cookbook, section 9.5, "Defining an adorner that can be modified by the user", has an adorner that takes some time to make a note lest you forget the second time you brush the book.
Complete code: https://github.com/blackmatrix7/python-learning/blob/master/python_cookbook/chapter_9/section_5/attach_wrapper.py
The decorator in the book (called the Accessor function in the book)
def attach_wrapper (obj, func=None): if is none: return Partial (attach_wrapper, obj) setattr (obj, func. __name__ , func) return func
This accessor function accepts two parameters, and obj is the object to be processed, and func is the decorated function. The effect of the implementation is to attach the adorned object to obj, so that obj has this method of Func.
When the accessor function executes to Func is none, the actual execution is Attach_wrapper (obj=wrapper), which just passes the object that needs to be processed by obj.
@attach_wrapper (wrapper) def set_message (newmsg): print(' Set Message ' ) nonlocal logmsg = newmsg
Using the adorner, it must be known that the set_message above the adorner, is actually equal to the following method
Attach_wrapper (wrapper) (Set_message)
For the above statement, you can also continue splitting
accessor function, when Func is None, returns a partial function return partial (attach_wrapper, obj)
This partial function actually generates a wrapper, and the wrapper itself accepts the decorated function.
So we get a partial function, which is also the wrapper
Partial_func = Attach_wrapper (wrapper)
Because the partial function already has an obj parameter, when called again, the setattr is executed (obj, func.__name__, func)
Add the decorated function to the object passed in by the adorner at this time.
Partial_func (Set_message)
If you do not understand, you can look at the following adorner.
The function of this adorner is equivalent to the accessor function above
def my_attach_wrapper (obj): """ If this is very easy to understand, attach this method to the object being passed in :p Aram obj: : return: "" " def _my_attach_wrapper (func): setattr (obj, func. __name__ , func) return _my_attach_wrapper
Python Cookbook "Defines an adorner that can be modified by the user" note