Last active
August 29, 2015 14:19
-
-
Save aminami1127/9315eacd3b0c2b26d860 to your computer and use it in GitHub Desktop.
General decorator
This file contains 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 -*- | |
import inspect | |
def multiply(func): | |
def _multiply(*args, **kwargs): | |
if inspect.getargspec(func).args[0] == 'self': | |
# 'if inspect.ismethod(func):' doesn't work in this situation, | |
# because when decorating the method isn't bounded to its class yet. | |
return func(*args, **kwargs) * (kwargs['num'] if 'num' in kwargs else args[1]) | |
else: | |
return func(*args, **kwargs) * (kwargs['num'] if 'num' in kwargs else args[0]) | |
return _multiply | |
@multiply | |
def func(num): | |
return num | |
class Calc(object): | |
@multiply | |
def method(self, num): | |
return num | |
# method, function or kwargs can be used. | |
c = Calc() | |
print c.method(2) | |
# 4 | |
print c.method(num=10) | |
# 100 | |
print func(5) | |
# 25 | |
print func(num=20) | |
# 400 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment