Last active
March 7, 2017 08:14
-
-
Save dberzano/5f80b3ec8f951d24d6426f61e96a055f to your computer and use it in GitHub Desktop.
Python decorators for class members
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
#!/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