Skip to content

Instantly share code, notes, and snippets.

@dberzano
Last active March 7, 2017 08:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dberzano/5f80b3ec8f951d24d6426f61e96a055f to your computer and use it in GitHub Desktop.
Save dberzano/5f80b3ec8f951d24d6426f61e96a055f to your computer and use it in GitHub Desktop.
Python decorators for class members
#!/usr/bin/env python
# Will print:
# init method
# decorator here
# called with a message
# 12345
# modern decorator here with decorator with a message
# yabba with another message
# 54321
def mydecorator(f):
# Decorator taking no arguments
def fn(self, *x, **y):
print "decorator here"
return f(self, *x, **y)
return fn
def mydecoratormsg(decmsg):
# Decorator taking arguments
def mydecorator(f):
def fn(self, *x, **y):
print "modern decorator here with %s" % decmsg
return f(self, *x, **y)
return fn
return mydecorator
class MyClass(object):
def __init__(self):
print "init method"
@mydecorator
def callmemaybe(self, message):
print "called with %s" % message
return 12345
@mydecoratormsg("decorator with a message")
def callmeyabba(self, message):
print "yabba with %s" % message
return 54321
m = MyClass()
print m.callmemaybe("a message")
print m.callmeyabba("another message")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment