Decorators in python
In Decorators, functions are taken as the argument into another function and then called inside the wrapper function.
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.
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.
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)
Problem¶
See the problem by clicking on the following link: Standardize Mobile Number Using Decorators
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.
1234567891011121314151617181920212223242526272829303132333435def 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: