Reason:Area of visibility. You may have wanted to turn it into a function to simplify the code inside the function, but at the same time, you don't want internal support functions to be out.For example, you have a function that accepts the list parameters, makes operations and returns the result. The code inside repeats itself, and we have to do something about it:def pow_and_sum(items_1, items_2, items_3) -> int:
items_1 = map(int, items_1)
items_2 = map(int, items_2)
items_3 = map(int, items_3)
items_1 = map(lambda x: pow(x, 2), items_1)
items_2 = map(lambda x: pow(x, 2), items_2)
items_3 = map(lambda x: pow(x, 2), items_3)
return sum(items_1) + sum(items_2) + sum(items_3)
The normal solution of the repetitive code is to turn it into a function, because that function is very specific, and we don't want it to be seen globally, creating it in local visibility:def pow_and_sum(items_1, items_2, items_3) -> int:
def do(items):
items = map(int, items)
items = map(lambda x: pow(x, 2), items)
return sum(map(int, items))
return do(items_1) + do(items_2) + do(items_3)
print(pow_and_sum('123', [1, 2], ['1', 4])) # 36
This is also used in: https://ru.wikipedia.org/wiki/%D0%97%D0%B0%D0%BC%D1%8B%D0%BA%D0%B0%D0%BD%D0%B8%D0%B5_(%D0%BF%D1%80%D0%BE%D0%B3%D1%80%D0%B0%D0%BC%D0%BC%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D0%B5) # multiplier возвращает функцию умножения на n
def multiplier(n):
def mul(k):
return n * k
return mul
mul3 - функция, умножающая на 3
mul3 = multiplier(3)
print(mul3(3), mul3(5)) # 9 15
https://ru.wikipedia.org/wiki/%D0%9A%D0%B0%D1%80%D1%80%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D0%B5 def my_sum(x, y, z):
return x + y + z
def foo(x):
def a(y):
def b(z):
return my_sum(x, y, z)
return b
return a
print(foo(1)(2)(3)) # 6
print(foo("1")("2")("3")) # 123
https://ru.wikipedia.org/wiki/%D0%94%D0%B5%D0%BA%D0%BE%D1%80%D0%B0%D1%82%D0%BE%D1%80_(%D1%88%D0%B0%D0%B1%D0%BB%D0%BE%D0%BD_%D0%BF%D1%80%D0%BE%D0%B5%D0%BA%D1%82%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D1%8F) def makebold(fn):
def wrapped(*args, **kwargs):
return "<b>" + fn(*args, **kwargs) + "</b>"
return wrapped
def makeitalic(fn):
def wrapped(*args, **kwargs):
return "<i>" + fn(*args, **kwargs) + "</i>"
return wrapped
def upper(fn):
def wrapped(*args, **kwargs):
return fn(*args, **kwargs).upper()
return wrapped
@makebold
@makeitalic
@upper
def hello(text):
return text
print(hello('Hello World!')) # <b><i>HELLO WORLD!</i></b>