Detailed explanation of closures and decorators in Python
Closure is an important grammatical structure in functional programming. Closure is also a structure for organizing code, which also improves the reusability of code.
If in an inline function, a variable in the outer function (but not in the global scope) is referenced, then the inline function is considered a closure.
Variables defined within an external function but referenced or used by an internal function are called free variables.
To summarize, creating a closure must meet the following points:
1. There must be an embedded function
2. The embedded function must reference the variables in the external function
3. The return value of the external function must be the embedded function
1 .Closure usage example
Let’s first look at an example of closure:
In [10]: def func(name): ...: def in_func(age): ...: print 'name:',name,'age:',age ...: return in_func ...: In [11]: demo = func('feiyu')In [12]: demo(19) name: feiyu age: 19
Here, when func
is called, a closure is generated——in_func
, and the closure holds the free variable - name
, so this also means that when the life cycle of the function func
ends, name
This variable still exists because it is referenced by the closure, so it will not be recycled.
In the function of python
, you can directly reference external variables, but you cannot rewrite external variables. Therefore, if you directly rewrite the variables of the parent function in the closure, an error will occur. Look at the following example:
Example of implementing a counting closure:
def counter(start=0):count = [start] def incr():count[0] += 1return countreturn incr a = counter() print 'a:',aIn [32]: def counter(start=0): ...: count = start ...: def incr(): ...: count += 1 ...: return count ...: return incr ...: In [33]: a = counter()In [35]: a() #此处会报错 UnboundLocalError: local variable 'count' referenced before assignment
should be used like the following:
In [36]: def counter(start=0): ...: count = [start] ...: def incr(): ...: count[0] += 1 ...: return count ...: return incr ...: In [37]: count = counter(5) In [38]: for i in range(10): ...: print count(), ...: [6] [7] [8] [9] [10] [11] [12] [13] [14] [15]
2. Pitfalls of using closures
In [1]: def create(): ...: return [lambda x:i*x for i in range(5)] #推导式生成一个匿名函数的列表 ...: In [2]: create()Out[2]: [<function __main__.<lambda>>, <function __main__.<lambda>>, <function __main__.<lambda>>, <function __main__.<lambda>>, <function __main__.<lambda>>]In [4]: for mul in create(): ...: print mul(2) ...: 88888
Isn’t the result very strange? This is a trap in the use of closures! Let’s see why?
In the above code, the function create
returns a list
which contains 4 function variables. These four functions all reference the loop variablei
, that is to say, they share the same variable i
, i
will change. When the function is called, the loop variable i
has been It is equal to 4, so all four functions return 8. If you need to use the value of a loop variable in a closure, use the loop variable as the default parameter of the closure or implement it through a partial function. The implementation principle is also very simple, that is, when the loop variable is passed into the function as a parameter, new memory will be applied for. The sample code is as follows:
In [5]: def create(): ...: return [lambda x,i=i:i*x for i in range(5)] ...: In [7]: for mul in create(): ...: print mul(2) ...: 02468
3, closure and decorator
The decorator is a kind of closure application, but it passes a function:
def addb(func):def wrapper():return '<b>' + func() + '</b>'return wrapperdef addli(func):def wrapper():return '<li>' + func() + '</li>'return wrapper @addb # 等同于 demo = addb(addli(demo)) @addli # 等同于 demo = addli(demo)def demo():return 'hello world' print demo() # 执行的是 addb(addku(demo))
During execution, the demo
function is first passed to addli
for decoration, and then the decorated function is passed to addb
for decoration. So the final result returned is:
<b><li>hello world</li></b>
4. Traps in decorators
When you write a decorator that acts on a function, the important meta-information of this function such as its name , docstrings, annotations, and parameter signatures will be lost.
def out_func(func):def wrapper(): func()return wrapper@out_funcdef demo():""" this is a demo. """print 'hello world.'if __name__ == '__main__': demo()print "__name__:",demo.__name__print "__doc__:",demo.__doc__
Look at the results:
hello world.__name__: wrapper__doc__: None
The function name and documentation string have become closure information. Fortunately, you can use the @wraps
decorator in the functools
library to annotate the underlying wrapper function.
from functools import wrapsdef out_func(func): @wraps(func)def wrapper(): func()return wrapper
Try the results yourself!
The above is the detailed content of Detailed explanation of closures and decorators in Python. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.
