Created
November 4, 2020 06:55
-
-
Save thanakijwanavit/5d4041d756be13579c1e2edceb4f81be to your computer and use it in GitHub Desktop.
wrap function to add method to a class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#export | |
from functools import wraps # This convenience func preserves name and docstring | |
def add_method(cls): | |
def decorator(func): | |
@wraps(func) | |
def wrapper(self, *args, **kwargs): | |
return func(self, *args, **kwargs) | |
setattr(cls, func.__name__, wrapper) | |
# Note we are not binding func, but wrapper which accepts self but does exactly the same as func | |
return func # returning func means func can still be used normally | |
return decorator |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment