Decorators in python
In Decorators, functions are taken as the argument into another function and then called inside the wrapper function.
# Create a function to add two numbers
def addition(x, y):
print(x+y)
# calling the addition function
addition(101, 120)
Our function is working nicely. We want to use this function as an argument to our wrapper function. Let's create our wrapper function and pass 'addition' function as a parameter into wrapper function.
a, b = 101, 120
def wrapper(function):
return function(var1, var2)
def addition(x, y):
print(a+b)
addition = wrapper(addition)
addition(a, b)
This gives use 'NameError' as name 'var1' is not defined. So, what can we do to solve this issue?
We may create another function inside wrapper function to input arguments.
a, b = 101, 120
def wrapper(function): # wrapper function will input function as parameter
def inner(var1, var2): # inner function will input variables as parameters
function(var1, var2)
return inner
def addition(x, y):
print(a+b)
addition = wrapper(addition)
addition(a, b)
def addition(x, y):
print(a+b)
addition = wrapper(addition)
addition(a, b)
We may replace the above code with the following code.
@wrapper
def addition(x, y):
print(a+b)
addition(a, b)
a, b = 101, 120
def wrapper(function):
def inner(var1, var2):
function(var1, var2)
return inner
@wrapper
def addition(x, y):
print(a+b)
addition(a, b)
Problem¶
See the problem by clicking on the following link: Standardize Mobile Number Using Decorators
def wrapper(function):
def fun(phoneNumber):
function(["+91 "+c[-10:-5]+" "+c[-5:] for c in phoneNumber])
return fun
@wrapper
def sort_phone(l):
print(*sorted(l), sep='\n')
n = 3
number = ['07895462130', '919875641230', '9195969878']
sort_phone(number)
Now, given a list of string type numbers : ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15'].
First, find palindromic integers among them. Second, Square all of them. Third, print the sum of the squared palindromic integers.
def wrapper1(function):
def palindromicInteger():
n = function()
palindromicInt = [int(i) for i in n if i == i[::-1]]
print("Palindromic integers are : ", palindromicInt)
return palindromicInt
return palindromicInteger
def wrapper2(function):
def square():
n = function()
squared = [i**2 for i in n]
print("Square of each palindromic integer are : ", squared)
return squared
return square
def wrapper3(function):
def addition():
n = function()
result = sum(n)
print("Sum of the squared palindromic integers are : ", result)
return result
return addition
@wrapper3
@wrapper2
@wrapper1
def number():
return ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15']
print(number())
@wrapper3
@wrapper2
@wrapper1
def number()
Above code indicates wrapper3(wrapper2(wrapper1(number)))
No comments: