Skip to content

Instantly share code, notes, and snippets.

@dboyliao
Last active August 9, 2017 15:30
Show Gist options
  • Select an option

  • Save dboyliao/e933bbadb11fe25b6089c3d21eac02ef to your computer and use it in GitHub Desktop.

Select an option

Save dboyliao/e933bbadb11fe25b6089c3d21eac02ef to your computer and use it in GitHub Desktop.
python class decorator example (Just for fun XDD)
# -*- 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