Last active
August 29, 2015 14:06
-
-
Save deemson/5b0b3732346402650442 to your computer and use it in GitHub Desktop.
Demo of decorators usage in Python
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 function_decorator(f): | |
print('decorating {}'.format(f.__name__)) | |
def wrapper(*args, **kwargs): | |
print('calling {}'.format(f.__name__)) | |
return wrapper | |
@function_decorator | |
def decorated_function(): | |
print('actual call') | |
decorated_function() | |
decorated_function() | |
class class_decorator(): | |
def __init__(self, clazz): | |
self.clazz = clazz | |
print('decorating {}'.format(clazz)) | |
def __call__(self): | |
print('creating an instance of {}'.format(self.clazz)) | |
return self.clazz() | |
@class_decorator | |
class DecoratedClass(): | |
@function_decorator | |
def decorated_method(self): | |
print('called class decorated method') | |
dc = DecoratedClass() | |
dc.decorated_method() | |
@class_decorator | |
def class_decorated_function(): | |
print('actual call') | |
class_decorated_function() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment