Python Tutorial
@my_decorator def show_message(msg): # my_decorator stuff goes here return msg;
def my_decorator(func): def decorator(): print("Before func() is called.") func() print("After func() is called.") return decorator; def show_message(): print("Welcome to python decorators!"); show_message = my_decorator(show_message); show_message();Output:
$ python test_decorators.py Before func() is called. Welcome to python decorators! After func() is called.
def my_decorator(func): def decorator(): print("Before func() is called.") func() print("After func() is called.") return decorator; if __name__ == "__main__": my_decorator()
from decorators import my_decorator; @my_decorator def show_message(): print("Welcome to python decorators!"); show_message();Output:
$ python test_decorators.py Before func() is called. Welcome to python decorators! After func() is called.
from time import sleep def my_decorator(function): """ Adds string contenation and sleeping time in decorator. """ def decorator(*args, **kwargs): sleep(2) return "Welcome to " + function(*args, **kwargs) return decorator; @my_decorator def show_message(msg): return msg; print(show_message("python decorator!"));Output:
$ python test_decorators1.py Welcome to python decorator!
def add_decorator(add_val): """ Adds decorator param with function return value. """ def addition_generator(old_function): def new_function(*args, **kwds): return add_val + old_function(*args, **kwds); return new_function; return addition_generator; #it returns the new generator @add_decorator(5) def addition(val): return val; print("sum: " + str(addition(6)));Output:
$ python test_decorators1.py sum: 11
from time import sleep def my_decorator(function): """ Adds string contenation and sleeping time in decorator. """ def decorator(*args, **kwargs): sleep(2) return "sum: " + str(function(*args, **kwargs)); return decorator; def add_decorator(add_val): """ Adds string contenation and sleeping time in decorator. """ def addition_generator(old_function): def new_function(*args, **kwds): return add_val + old_function(*args, **kwds); return new_function; return addition_generator; #it returns the new generator @my_decorator @add_decorator(5) def addition(val): return val; print(addition(6));Output;
$ python test_decorators1.py sum: 11
def singleton(class_name): object_list = {}; def get_object(): if class_name not in object_list: object_list[class_name] = class_name(); return object_list[class_name]; return get_object; @singleton class Math(object): pass a = Math(); print "a: ", id(a); b = Math(); print "b: ", id(b) print "a and b is: ", id(a) == id(b)Output:
$ python test_decorators2.py a: 140342052585296 b: 140342052585296 a and b is: True
Python Tutorial
Privacy Policy | Copyright2020 - All Rights Reserved. | Contact us | Report website issues in Github | Facebook page | Google+ page