Last active
January 17, 2018 16:46
-
-
Save harunyasar/dec944f864dc3aa745b51faf745bb796 to your computer and use it in GitHub Desktop.
Function-based decorators
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
def add2(func): | |
def wrapper(*args, **kwargs): | |
return func(*args, **kwargs) + 2 | |
return wrapper | |
@add2 | |
def foo(number): | |
return number * 2 | |
f = foo(5) | |
print(f) | |
def add5(func): | |
def wrapper(*args, **kwargs): | |
return func(*args, **kwargs) + 5 | |
return wrapper | |
def bar(number): | |
return number ** 2 | |
# Can also be defined without decorator function. | |
bar = add5(bar) | |
f = bar(2) | |
print(f) | |
# What if I want to increment by 8 must I create a new function add8? No. | |
# And it is not a decorator this is a function which going to return a decorator function. | |
def add(number): | |
def decorator(func): | |
def wrapper(*args, **kwargs): | |
return func(*args, *kwargs) + number | |
return wrapper | |
return decorator | |
def multiply(number): | |
def decorator(func): | |
def wrapper(*args, **kwargs): | |
return func(*args, *kwargs) * number | |
return wrapper | |
return decorator | |
@multiply(3) | |
@add(8) | |
def baz(number): | |
return number | |
f = baz(8) | |
print(f) | |
# There is an another way to calling the function | |
def qux(number): | |
return number ** 3 | |
qux = add(8)(qux) | |
print(qux(3)) | |
# This kind of functions can be used in a method. But it has to changed with this way | |
# Give your attention to function call in wrapper. | |
def add(number): | |
def decorator(func): | |
def wrapper(self, *args, **kwargs): | |
return func(self, *args, **kwargs) + number | |
return wrapper | |
return decorator | |
class Foo: | |
def __init__(self, number): | |
self.number = number | |
@add(2) | |
def bar(self): | |
return self.number ** 2 | |
f = Foo(8) | |
print(f.bar()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment