This is my 25th day of #100DaysOfCode and Python. Today I am not able to give my time more than 2 hours. Because of my own personal work. So I learned something about python decorators. And Tried to do some code on it.
Some of the code which I practice today and tried to write are given below.
Some Simple Code On Python Decorators
While I studied I learned that python has a interesting features called decorators to add functionality to an existing code. This is also called meta programming because a part of the program tried to modify another part of program.
def make_pretty(func): def inner(): print("I got decorated") func() return inner def ordinary(): print("I am ordinary") pretty = make_pretty(ordinary) pretty() When this program run its output is
I got decorated I am ordinary In the above code make_pretty is decorator, ordinary got decorated and returned function was given by the name preety.
def smart_divide(func): def inner(a, b): print("I am going to divide", a, "and", b) if b == 0: print("Whoops! cannot divide") return return func(a, b) return inner @smart_divide def divide(a, b): print(a/b) divide(2,0) Above function is the example of decorator with parameter. Here a and b are two parameter .
Here is some other example of decorators,
def printer(text): print(text) printer = star(percent(printer)) printer('Durga') Output of this code is
****************************** %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Durga %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ******************************
Day 25 of #100DaysOfCode and #Python
— Durga Pokharel (@mathdurga) January 18, 2021
* Python functions , Argument and Parameter
* Python Higher Order Function
* Python Decorators
* Some Simple Code On Python Decorators Tried To Learn Today#100DaysOfCode ,#CodeNewbie ,#beginner ,#Python pic.twitter.com/t302xx1TlK
Top comments (2)
Keep going, we're going along with u :)
Thank you for support 🤗