Skip to content

Instantly share code, notes, and snippets.

@jamielennox
Created December 6, 2013 00:11
Show Gist options
  • Save jamielennox/7816497 to your computer and use it in GitHub Desktop.
Save jamielennox/7816497 to your computer and use it in GitHub Desktop.
Wrapping a class function by a decorator example.
class MyClass(object):
def __repr__(self):
return "<MyClass>"
def my_hello(self):
print "hello from", self
mc = MyClass()
mc.my_hello() # prints "hello from <MyClass>"
def goodbye_func(self):
print "goodbye from", self
def sayonara_func(self):
print "sayanora from", self
# it's just a normal function that takes a parameter
goodbye_func(None) # prints "goodbye from None"
# late assign a function to a class
MyClass.my_goodbye = goodbye_func
# still works on initialized classes
mc.my_goodbye() # prints "goodbye from <MyClass>"
# now to wrap an object around a class
def wrap(cls):
def wrapper(f):
original_func = getattr(cls, f.__name__)
def inner(self, *args, **kwargs):
return f(self, original_func, *args, **kwargs)
setattr(cls, f.__name__, inner)
return wrapper
@wrap(MyClass)
def my_goodbye(self, func):
print "enter from", self
func(self)
print "exit from", self
print mc.my_goodbye() # prints "enter from <MyClass>, goodbye from <MyClass>, exit from <MyClass>"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment