Last active
December 23, 2018 07:07
-
-
Save BitAndQuark/85b8f51791f5955d8a325dda273a88e3 to your computer and use it in GitHub Desktop.
Python decorator
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
# Python decorator is a convenient way to wrap functions with reused logic | |
def Dec(F): | |
def G(*args): | |
print('wrapper starts') | |
F(*args) | |
print('wrapper ends') | |
return G | |
@Dec | |
def F(*args): | |
print('F executes') | |
F('hi') | |
# output # | |
#>> wrapper starts | |
#>> F executes | |
#>> wrapper ends | |
# Class decoratr # | |
class D: | |
def __init__(self, F) -> None: | |
self.f = F | |
def __call__(self, *args, **kwargs): | |
print('wrapper class starts') | |
self.f(*args, **kwargs) | |
print('wrapper class ends') | |
@D | |
def F(*args, **kwargs): | |
print('F executes') | |
F() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment