Python中decorator使用实例
在我以前介绍 Python 2.4 特性的Blog中已经介绍过了decorator了,不过,那时是照猫画虎,现在再仔细描述一下它的使用。
关于decorator的详细介绍在 Python 2.4中的What's new中已经有介绍,大家可以看一下。
如何调用decorator
基本上调用decorator有两种形式
第一种:
@A
def f ():
这种形式是decorator不带参数的写法。最终 Python 会处理为:
f = A(f)
还可以扩展成:
@A
@B
@C
def f ():
最终 Python 会处理为:
f = A(B(C(f)))
注:文档上写的是@A @B @C的形式,但实际上是不行的,要写成多行。而且执行顺序是按函数调用顺序来的,先最下面的C,然后是B,然后是A。因此,如果decorator有顺序话,一定要注意:先要执行的放在最下面,最后执行的放在最上面。(应该不存在这种倒序的关系)
第二种:
@A(args)
def f ():
这种形式是decorator带参数的写法。那么 Python 会处理为:
def f():
_deco = A(args)
f = _deco(f)
可以看出, Python 会先执行A(args)得到一个decorator函数,然后再按与第一种一样的方式进行处理。
decorator函数的定义
每一个decorator都对应有相应的函数,它要对后面的函数进行处理,要么返回原来的函数对象,要么返回一个新的函数对象。请注意,decorator只用来处理函数和类方法。
第一种:
针对于第一种调用形式
def A(func):
#处理func
#如func.attr='decorated'
return func
@A
def f(args):pass
上面是对func处理后,仍返回原函数对象。这个decorator函数的参数为要处理的函数。如果要返回一个新的函数,可以为:
def A(func):
def new_func(args):
#做一些额外的工作
return func(args) #调用原函数继续进行处理
return new_func
@A
def f(args):pass
要注意 new_func的定义形式要与待处理的函数相同,因此还可以写得通用一些,如:
def A(func):
def new_func(*args, **argkw):
#做一些额外的工作
return func(*args, **argkw) #调用原函数继续进行处理
return new_func
@A
def f(args):pass
可以看出,在A中定义了新的函数,然后A返回这个新的函数。在新函数中,先处理一些事情,比如对参数进行检查,或做一些其它的工作,然后再调原始的函数进行处理。这种模式可以看成,在调用函数前,通过使用decorator技术,可以在调用函数之前进行了一些处理。如果你想在调用函数之后进行一些处理,或者再进一步,在调用函数之后,根据函数的返回值进行一些处理可以写成这样:
def A(func):
def new_func(*args, **argkw):
result = func(*args, **argkw) #调用原函数继续进行处理
if result:
#做一些额外的工作
return new_result
else:
return result
return new_func
@A
def f(args):pass
第二种:
针对第二种调用形式
在文档上说,如果你的decorator在调用时使用了参数,那么你的decorator函数只会使用这些参数进行调用,因此你需要返回一个新的decorator函数,这样就与第一种形式一致了。
def A(arg):
def _A(func):
def new_func(args):
#做一些额外的工作
return func(args)
return new_func
return _A
@A(arg)
def f(args):pass
可以看出A(arg)返回了一个新的 decorator _A。
decorator的应用场景
不过我也一直在想,到底decorator的魔力是什么?适合在哪些场合呢?是否我需要使用它呢?
decorator的魔力就是它可以对所修饰的函数进行加工。那么这种加工是在不改变原来函数代码的情况下进行的。有点象我知道那么一点点的AOP(面向方面编程)的想法。
它适合的场合我能想到的列举出下:
1.象文档中所说,最初是为了使调用staticmethod和classmethod这样的方法更方便
2.在某些函数执行前做一些工作,如web开发中,许多函数在调用前需要先检查一下用户是否已经登录,然后才能调用
3.在某此函数执行后做一些工作,如调用完毕后,根据返回状态写日志
4.做参数检查
可能还有许多,你可以自由发挥想象
那么我需要用它吗?
我想那要看你了。不过,我想在某些情况下,使用decorator可以增加程序的灵活性,减少耦合度。比如前面所说的用户登录检查。的确可以写一个通用的登录检查函数,然后在每个函数中进行调用。但这样会造成函数不够灵活,而且增加了与其它函数之间的结合程度。如果用户登录检查功能有所修改,比如返回值的判断发生了变化,有可能每个用到它的函数都要修改。而使用decorator不会造成这一问题。同时使用decorator的语法也使得代码简单,清晰(一但你熟悉它的语法的话)。当然你不使用它是可以的。不过,这种函数之间相互结合的方式,更符合搭积木的要求,它可以把函数功能进一步分解,使得功能足够简单和单一。然后再通过decorator的机制灵活的把相关的函数串成一个串,这么一想,还真是不错。比如下面:
@A
@B
def account(args):pass
假设这是一个记帐处理函数,account只管记帐。但一个真正的记帐还有一些判断和处理,比如:B检查帐户状态,A记日志。这样的效果其实是先检查B、通过在A中的处理可以先执行account,然后再进行记日志的处理。象搭积木一样很方便,改起来也容易。甚至可以把account也写成decorator,而下面执行的函数是一个空函数。然后再通过配置文件等方法,将decorator的组合保存起来,就基本实现功能的组装化。是不是非常理想。
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

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

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.

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 extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

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.

VS Code is available on Mac. It has powerful extensions, Git integration, terminal and debugger, and also offers a wealth of setup options. However, for particularly large projects or highly professional development, VS Code may have performance or functional limitations.

The key to running Jupyter Notebook in VS Code is to ensure that the Python environment is properly configured, understand that the code execution order is consistent with the cell order, and be aware of large files or external libraries that may affect performance. The code completion and debugging functions provided by VS Code can greatly improve coding efficiency and reduce errors.
