Last active
August 9, 2017 15:30
-
-
Save dboyliao/e933bbadb11fe25b6089c3d21eac02ef to your computer and use it in GitHub Desktop.
python class decorator example (Just for fun XDD)
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
| # -*- coding:utf-8 -*- | |
| from __future__ import print_function | |
| from functools import wraps | |
| def log_deco(func): | |
| @wraps(func) | |
| def wrapped(*args, **kwargs): | |
| print("calling {}".format(func.__name__)) | |
| return func(*args, **kwargs) | |
| return wrapped | |
| def cls_deco(cls): | |
| for name, method in cls.__dict__.items(): | |
| if not name.startswith("_"): | |
| setattr(cls, name, log_deco(method)) | |
| return cls | |
| @cls_deco | |
| class MyClass(object): | |
| def add_one(self, x): | |
| return x+1 | |
| def sub_one(self, x): | |
| return x-1 | |
| if __name__ == "__main__": | |
| me = MyClass() | |
| print(me.add_one(3)) | |
| print(me.sub_one(10)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment