python中函数总结之装饰器闭包详解
1、前言
函数也是一个对象,从而可以增加属性,使用句点来表示属性。
如果内部函数的定义包含了在外部函数中定义的对象的引用(外部对象可以是在外部函数之外),那么内部函数被称之为闭包。
2、装饰器
装饰器就是包装原来的函数,从而在不需要修改原来代码的基础之上,可以做更多的事情。
装饰器语法如下:
@deco2 @deco1 def func(arg1,arg2...): pass
这个表示了有两个装饰器的函数,那么表示的含义为:func = deco2(deco1(func))
无参装饰器语法如下:
@deco def func(): pass
表示的含义为func = deco(func)
有参装饰器语法如下:
@deco(deco_args) def func(): pass
表示的含义为:func = deco(deco_args)(func)
多个装饰器有的有参数有的没参数,语法如下:
@deco2(arg1,arg2) @deco1 def func(): pass
表示的含义为foo = deco2(arg1,arg2)deco1(func)
装饰器实际上就是函数,接受的也是函数对象。
在执行函数之前,可以运行预备代码,也可以在执行代码后做一些清理工作。
看见装饰器的时候,很可能在里面找到一些代码,它定义了某个函数,并在定义内的某处嵌入了对目标函数的调用或者至少一点引用。
3、装饰器作用
装饰器的作用如下:
引入日志;增加计时逻辑来检测性能;给函数加入了事物的能力
以下例子表示为引入了计时的逻辑来检测性能,如下:
#!/usr/bin/env python from time import ctime,sleep def tsfunc(func): #装饰器函数接受的是一个函数对象 def wrappedFunc(): print '[%s] %s() called' % (ctime(),func.__name__) return func() #在这里调用了函数对象,也就是表示装饰器是装饰了原来的函数,从而在原来函数的基础上进行了一些操作 return wrappedFunc @tsfunc #装饰器 def foo(): pass foo() sleep(4) for i in range(2): sleep(1) foo()
执行结果如下:
[root@python 420]# python deco.py [Tue Apr 19 16:15:01 2016] foo() called [Tue Apr 19 16:15:06 2016] foo() called [Tue Apr 19 16:15:07 2016] foo() called
在装饰器函数中,增加了时间戳并且调用了目标函数,装饰器的返回值是一个包装了函数。
4、闭包
如果在一个内部函数里,对在外部作用于(但不是全局作用域)的变量进行引用,那么内部函数被认为是闭包closure,定义在外部函数内的但由内部函数引用或者使用的变量称之为自由变量。
闭包的主要作用如下:
安装计算;隐藏状态;在函数对象和作用域中随意的切换。
回调就是函数,闭包也是函数,但是能携带一点额外的作用域。
#!/usr/bin/env python def counter(start_at=0): count = [start_at] def incr(): count[0] += 1 return count[0] return incr count= counter(5) print count() print count()
在上面的例子可以看到,函数内部的函数incr引用了外部的变量count,并且每次进行加一,从而这个变量count称之为自由变量。
以上这篇python中函数总结之装饰器闭包详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

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

AI Hentai Generator
Generate AI Hentai for free.

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

How to download DeepSeek Xiaomi? Search for "DeepSeek" in the Xiaomi App Store. If it is not found, continue to step 2. Identify your needs (search files, data analysis), and find the corresponding tools (such as file managers, data analysis software) that include DeepSeek functions.

The key to using DeepSeek effectively is to ask questions clearly: express the questions directly and specifically. Provide specific details and background information. For complex inquiries, multiple angles and refute opinions are included. Focus on specific aspects, such as performance bottlenecks in code. Keep a critical thinking about the answers you get and make judgments based on your expertise.

Just use the search function that comes with DeepSeek. Its powerful semantic analysis algorithm can accurately understand the search intention and provide relevant information. However, for searches that are unpopular, latest information or problems that need to be considered, it is necessary to adjust keywords or use more specific descriptions, combine them with other real-time information sources, and understand that DeepSeek is just a tool that requires active, clear and refined search strategies.

DeepSeek is not a programming language, but a deep search concept. Implementing DeepSeek requires selection based on existing languages. For different application scenarios, it is necessary to choose the appropriate language and algorithms, and combine machine learning technology. Code quality, maintainability, and testing are crucial. Only by choosing the right programming language, algorithms and tools according to your needs and writing high-quality code can DeepSeek be successfully implemented.

Question: Is DeepSeek available for accounting? Answer: No, it is a data mining and analysis tool that can be used to analyze financial data, but it does not have the accounting record and report generation functions of accounting software. Using DeepSeek to analyze financial data requires writing code to process data with knowledge of data structures, algorithms, and DeepSeek APIs to consider potential problems (e.g. programming knowledge, learning curves, data quality)

Python is an ideal programming introduction language for beginners through its ease of learning and powerful features. Its basics include: Variables: used to store data (numbers, strings, lists, etc.). Data type: Defines the type of data in the variable (integer, floating point, etc.). Operators: used for mathematical operations and comparisons. Control flow: Control the flow of code execution (conditional statements, loops).

Pythonempowersbeginnersinproblem-solving.Itsuser-friendlysyntax,extensivelibrary,andfeaturessuchasvariables,conditionalstatements,andloopsenableefficientcodedevelopment.Frommanagingdatatocontrollingprogramflowandperformingrepetitivetasks,Pythonprovid

Detailed explanation of DeepSeekAPI access and call: Quick Start Guide This article will guide you in detail how to access and call DeepSeekAPI, helping you easily use powerful AI models. Step 1: Get the API key to access the DeepSeek official website and click on the "Open Platform" in the upper right corner. You will get a certain number of free tokens (used to measure API usage). In the menu on the left, click "APIKeys" and then click "Create APIkey". Name your APIkey (for example, "test") and copy the generated key right away. Be sure to save this key properly, as it will only be displayed once
