Nested function usage and closures in Python

A Nested function is a function defined within another function (ie: an enclosing function).

So, in what situations are nested functions generally used?

  • Encapsulation - Data Hiding
  • Implement the DRY principle
  • Closure

In addition, there are other uses of nested functions, but these are more commonly used. In addition, the content of the closure is relatively rich, which will be shared separately later.

Encapsulation - Data Hiding

Inner functions can be used to protect them from changes outside the function, i.e. to hide them from the global scope.

Let's see a simple example - find a multiple of a number n:

>>> def outer(n):
...     def inner_multiple(n):  # 从外部代码隐藏
...         return n * 2
...     num = inner_multiple(n)
...     print(num)
... 
>>>

Attempting to call inner_multiple(n)will throw an error:

>>> outer(5)
10
>>> 
>>> inner_multiple(5)  # 外部无法访问
...
NameError: name 'inner_multiple' is not defined

This is because it is defined inside outer() and is hidden, so it cannot be accessed from outside.

Implement the DRY principle

DRY (Don't Repeat Yourself) - refers to the avoidance of repetitive code in programming and calculations, as this reduces flexibility, simplicity, and may lead to inconsistencies between codes.

DRY is more of an architectural design idea. Everything in the software development process may be repeated, ranging from standards, frameworks, and development processes; to components and interfaces; to small functions and codes, all of which are purely self-repetitive. And what DRY advocates is that all this self-duplication should be eliminated in the software development process.

In-depth python closures

Closure concept: In an inner function, a reference is made to a variable in the outer scope (and generally the return value of the outer function is the inner function), then the inner function is considered to be a closure. Take a chestnut first:

insert image description here
An incrementBy function is defined in the function startAt, incrementBy accesses the variable of the external function startAt, and the return value of the function is the incrementBy function. Note that python can return a function, which is also one of the characteristics of python.

insert image description here
In the above code, a is actually a function, and the result of the above code execution:

insert image description here
It is not difficult to see from the result that a is the function incrementBy instead of startAt, which is a bit confusing, but it is not difficult to understand, because the return is the incrementBy function.

insert image description here
The output is:
insert image description here
If function a is called, the result is the integer value of the passed parameter plus.

Guess you like

Origin blog.csdn.net/weixin_43838785/article/details/122919656