Home Backend Development Python Tutorial python 装饰器功能以及函数参数使用介绍

python 装饰器功能以及函数参数使用介绍

Jun 16, 2016 am 08:47 AM
python Decorator

简单的说:装饰器主要作用就是对函数进行一些修饰,它的出现是在引入类方法和静态方法的时候为了定义静态方法出现的。例如为了把foo()函数声明成一个静态函数

复制代码 代码如下:

class Myclass(object):
def staticfoo():
............
............
staticfoo = staticmethod(staticfoo)

可以用装饰器的方法实现:
复制代码 代码如下:

class Myclass(object):
  @staticmethod  
  def staticfoo():
    .........
    .........

这个例子很明显很容易就可以看懂。

说到这里我们举一个下面的例子,这个例子里面同时涉及到一个重要内容,就是对于python中的函数的本质理解。

代码:
复制代码 代码如下:

# -*- coding: utf-8 -*-
from time import ctime
from time import sleep
def ftfunc(func):
def timef():
print "[%s] %s() called" % (ctime(),func.__name__)
return func()
return timef

@ftfunc
def foo():
print 'hello'

if __name__ == '__main__':

foo()
sleep(2)

for i in range(2):
sleep(1)
foo()

运行这段代码;我们可以看到终端依次会输出以下内容:


其中ftfunc函数是我们自己自定义的一个函数,这个函数是以一个函数作为参数的函数,这也就满足了作为一个装饰器的要求,根据上面我们对于装饰器的等价变换规则,这段代码

复制代码 代码如下:

@ftfunc
def foo():
print 'hello'

可以转换成以下的代码:
复制代码 代码如下:

def foo():
print 'hello'

foo = ftfunc(foo)

再结合上面原来的代码我们很快就可以体会到了装饰器的作用。

但是我在编写这段代码的时候,有一个地方打错了:

这段代码:
复制代码 代码如下:

return func()
return timef

被我写成了:
复制代码 代码如下:

return func
return timef

于是输出结果就是不一样,后来终于发现了一个重要的概念:"foo"是函数对象的引用,而"foo()"是函数对象的调用。关于对象引用是python的重要的基础概念,在python中一切都是对象,同时类型是属于对象,而不是变量。一切的变量只是对象的引用,相当于让这个变量指向这个对象。“foo”正好可以理解成一个变量,只不过是它指向一个函数的对象。而“foo()”是函数对象的调用,即调用这个对象,是要执行这个函数的功能的。这里需要慢慢理解品味。基于此:

这样的一段代码运行结果和刚才是一模一样的。注意比较与刚才那段代码的不同之处,更加有利于理解。
复制代码 代码如下:

# -*- coding: utf-8 -*-
from time import ctime
from time import sleep
def ftfunc(func):
def timef():
print "[%s] %s() called" % (ctime(),func.__name__)
return func
return timef

@ftfunc
def foo():
print 'hello'

if __name__ == '__main__':

foo()()
sleep(2)

for i in range(2):
sleep(1)
foo()()

此代码运行结果:

其实还可以分别对返回的timef函数加上括号,看看结果会是怎么样的。可以更好理解python中函数的概念。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1671
14
PHP Tutorial
1276
29
C# Tutorial
1256
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

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.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

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.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

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.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

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.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

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.

Golang vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

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".

See all articles