Created
June 24, 2017 10:58
-
-
Save erizhang/7751a6b32c0c7e3c9cbfb6aca3c37afb to your computer and use it in GitHub Desktop.
Learn python decorator samples
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 a_decorator_passing_arbitrary_arguments(function_to_decorate): | |
def wrapper(*args, **kwargs): | |
print "Do I have args?:" | |
print args | |
print kwargs | |
function_to_decorate(*args, **kwargs) | |
return wrapper | |
@a_decorator_passing_arbitrary_arguments | |
def function_with_no_argument(): | |
print "Python is cool, no argument here." | |
@a_decorator_passing_arbitrary_arguments | |
def function_with_arguments(a, b, c): | |
print a, b, c | |
@a_decorator_passing_arbitrary_arguments | |
def function_with_named_arguments(a, b, c, platypus="Why not ?"): | |
print "Do %s, %s and %s like platypus? %s" % \ | |
(a, b, c, platypus) | |
class Mary(object): | |
def __init__(self): | |
self.age = 31 | |
@a_decorator_passing_arbitrary_arguments | |
def sayYourAge(self, lie = -3): | |
print "I am %s, what do you think ?" % (self.age + lie) | |
def my_decorator(func): | |
print "I'm a ordinary function." | |
def wrapper(): | |
print "I'm a function returned by decorator." | |
func() | |
return wrapper | |
def lazzy_function(): | |
print "zzzzzzzz" | |
if __name__ == "__main__": | |
print "__________1__________" | |
function_with_no_argument() | |
print "__________2__________" | |
function_with_arguments(1, 2, 3) | |
print "__________3__________" | |
function_with_named_arguments("Bill", "Linux", "Steve", platypus = "Indeed!") | |
print "__________4__________" | |
m = Mary() | |
m.sayYourAge() | |
print "_____________________" | |
decorated_function = my_decorator(lazzy_function) | |
decorated_function() | |
@my_decorator | |
def haha(): | |
print "ahahahaha" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment