Home Backend Development Python Tutorial Python中的各种装饰器详解

Python中的各种装饰器详解

Jun 06, 2016 am 11:24 AM
python Decorator

Python装饰器,分两部分,一是装饰器本身的定义,一是被装饰器对象的定义。

一、函数式装饰器:装饰器本身是一个函数。

1.装饰函数:被装饰对象是一个函数

[1]装饰器无参数:

a.被装饰对象无参数:

代码如下:


>>> def test(func):
    def _test():
        print 'Call the function %s().'%func.func_name
        return func()
    return _test

>>> @test
def say():return 'hello world'

>>> say()
Call the function say().
'hello world'
>>>

b.被装饰对象有参数:

代码如下:


>>> def test(func):
    def _test(*args,**kw):
        print 'Call the function %s().'%func.func_name
        return func(*args,**kw)
    return _test

>>> @test
def left(Str,Len):
    #The parameters of _test can be '(Str,Len)' in this case.
    return Str[:Len]

>>> left('hello world',5)
Call the function left().
'hello'
>>>

[2]装饰器有参数:

a.被装饰对象无参数:

代码如下:


>>> def test(printResult=False):
    def _test(func):
        def __test():
            print 'Call the function %s().'%func.func_name
            if printResult:
                print func()
            else:
                return func()
        return __test
    return _test

>>> @test(True)
def say():return 'hello world'

>>> say()
Call the function say().
hello world
>>> @test(False)
def say():return 'hello world'

>>> say()
Call the function say().
'hello world'
>>> @test()
def say():return 'hello world'

>>> say()
Call the function say().
'hello world'
>>> @test
def say():return 'hello world'

>>> say()

Traceback (most recent call last):
  File "", line 1, in
    say()
TypeError: _test() takes exactly 1 argument (0 given)
>>>


由上面这段代码中的最后两个例子可知:当装饰器有参数时,即使你启用装饰器的默认参数,不另外传递新值进去,也必须有一对括号,否则编译器会直接将func传递给test(),而不是传递给_test()

b.被装饰对象有参数:

代码如下:


>>> def test(printResult=False):
    def _test(func):
        def __test(*args,**kw):
            print 'Call the function %s().'%func.func_name
            if printResult:
                print func(*args,**kw)
            else:
                return func(*args,**kw)
        return __test
    return _test

>>> @test()
def left(Str,Len):
    #The parameters of __test can be '(Str,Len)' in this case.
    return Str[:Len]

>>> left('hello world',5)
Call the function left().
'hello'
>>> @test(True)
def left(Str,Len):
    #The parameters of __test can be '(Str,Len)' in this case.
    return Str[:Len]

>>> left('hello world',5)
Call the function left().
hello
>>>


 
2.装饰类:被装饰的对象是一个类

[1]装饰器无参数:

a.被装饰对象无参数:

代码如下:


>>> def test(cls):
    def _test():
        clsName=re.findall('(\w+)',repr(cls))[-1]
        print 'Call %s.__init().'%clsName
        return cls()
    return _test

>>> @test
class sy(object):
    value=32

   
>>> s=sy()
Call sy.__init().
>>> s
<__main__.sy object at>
>>> s.value
32
>>>


b.被装饰对象有参数:

代码如下:


>>> def test(cls):
    def _test(*args,**kw):
        clsName=re.findall('(\w+)',repr(cls))[-1]
        print 'Call %s.__init().'%clsName
        return cls(*args,**kw)
    return _test

>>> @test
class sy(object):
    def __init__(self,value):
                #The parameters of _test can be '(value)' in this case.
        self.value=value

       
>>> s=sy('hello world')
Call sy.__init().
>>> s
<__main__.sy object at>
>>> s.value
'hello world'
>>>


 [2]装饰器有参数:

a.被装饰对象无参数:

代码如下:


>>> def test(printValue=True):
    def _test(cls):
        def __test():
            clsName=re.findall('(\w+)',repr(cls))[-1]
            print 'Call %s.__init().'%clsName
            obj=cls()
            if printValue:
                print 'value = %r'%obj.value
            return obj
        return __test
    return _test

>>> @test()
class sy(object):
    def __init__(self):
        self.value=32

       
>>> s=sy()
Call sy.__init().
value = 32
>>> @test(False)
class sy(object):
    def __init__(self):
        self.value=32

       
>>> s=sy()
Call sy.__init().
>>>

 b.被装饰对象有参数:
 

代码如下:


 >>> def test(printValue=True):
    def _test(cls):
        def __test(*args,**kw):
            clsName=re.findall('(\w+)',repr(cls))[-1]
            print 'Call %s.__init().'%clsName
            obj=cls(*args,**kw)
            if printValue:
                print 'value = %r'%obj.value
            return obj
        return __test
    return _test

>>> @test()
class sy(object):
    def __init__(self,value):
        self.value=value

       
>>> s=sy('hello world')
Call sy.__init().
value = 'hello world'
>>> @test(False)
class sy(object):
    def __init__(self,value):
        self.value=value

       
>>> s=sy('hello world')
Call sy.__init().
>>>
 


 二、类式装饰器:装饰器本身是一个类,借用__init__()和__call__()来实现职能

1.装饰函数:被装饰对象是一个函数

[1]装饰器无参数:

a.被装饰对象无参数:

代码如下:


>>> class test(object):
    def __init__(self,func):
        self._func=func
    def __call__(self):
        return self._func()

   
>>> @test
def say():
    return 'hello world'

>>> say()
'hello world'
>>>

b.被装饰对象有参数:

代码如下:


>>> class test(object):
    def __init__(self,func):
        self._func=func
    def __call__(self,*args,**kw):
        return self._func(*args,**kw)

   
>>> @test
def left(Str,Len):
    #The parameters of __call__ can be '(self,Str,Len)' in this case.
    return Str[:Len]

>>> left('hello world',5)
'hello'
>>>

 [2]装饰器有参数

a.被装饰对象无参数:

代码如下:


>>> class test(object):
    def __init__(self,beforeinfo='Call function'):
        self.beforeInfo=beforeinfo
    def __call__(self,func):
        def _call():
            print self.beforeInfo
            return func()
        return _call

   
>>> @test()
def say():
    return 'hello world'

>>> say()
Call function
'hello world'
>>>

或者:

代码如下:


 >>> class test(object):
    def __init__(self,beforeinfo='Call function'):
        self.beforeInfo=beforeinfo
    def __call__(self,func):
        self._func=func
        return self._call
    def _call(self):
        print self.beforeInfo
        return self._func()

   
>>> @test()
def say():
    return 'hello world'

>>> say()
Call function
'hello world'
>>>

 b.被装饰对象有参数:
 

代码如下:


 >>> class test(object):
    def __init__(self,beforeinfo='Call function'):
        self.beforeInfo=beforeinfo
    def __call__(self,func):
        def _call(*args,**kw):
            print self.beforeInfo
            return func(*args,**kw)
        return _call

   
>>> @test()
def left(Str,Len):
    #The parameters of _call can be '(Str,Len)' in this case.
    return Str[:Len]

>>> left('hello world',5)
Call function
'hello'
>>>
 

 或者:
 

代码如下:


 >>> class test(object):
    def __init__(self,beforeinfo='Call function'):
        self.beforeInfo=beforeinfo
    def __call__(self,func):
        self._func=func
        return self._call
    def _call(self,*args,**kw):
        print self.beforeInfo
        return self._func(*args,**kw)

   
>>> @test()
def left(Str,Len):
    #The parameters of _call can be '(self,Str,Len)' in this case.
    return Str[:Len]

>>> left('hello world',5)
Call function
'hello'
>>>
 


  2.装饰类:被装饰对象是一个类

[1]装饰器无参数:

a.被装饰对象无参数:

代码如下:


>>> class test(object):
    def __init__(self,cls):
        self._cls=cls
    def __call__(self):
        return self._cls()

   
>>> @test
class sy(object):
    def __init__(self):
        self.value=32

   
>>> s=sy()
>>> s
<__main__.sy object at>
>>> s.value
32
>>>

 b.被装饰对象有参数:
 

代码如下:


 >>> class test(object):
    def __init__(self,cls):
        self._cls=cls
    def __call__(self,*args,**kw):
        return self._cls(*args,**kw)

   
>>> @test
class sy(object):
    def __init__(self,value):
        #The parameters of __call__ can be '(self,value)' in this case.
        self.value=value

       
>>> s=sy('hello world')
>>> s
<__main__.sy object at>
>>> s.value
'hello world'
>>>
 

 [2]装饰器有参数:

a.被装饰对象无参数:

代码如下:


>>> class test(object):
    def __init__(self,printValue=False):
        self._printValue=printValue
    def __call__(self,cls):
        def _call():
            obj=cls()
            if self._printValue:
                print 'value = %r'%obj.value
            return obj
        return _call

   
>>> @test(True)
class sy(object):
    def __init__(self):
        self.value=32

       
>>> s=sy()
value = 32
>>> s
<__main__.sy object at>
>>> s.value
32
>>>

 b.被装饰对象有参数:
 

代码如下:


 >>> class test(object):
    def __init__(self,printValue=False):
        self._printValue=printValue
    def __call__(self,cls):
        def _call(*args,**kw):
            obj=cls(*args,**kw)
            if self._printValue:
                print 'value = %r'%obj.value
            return obj
        return _call

   
>>> @test(True)
class sy(object):
    def __init__(self,value):
        #The parameters of _call can be '(value)' in this case.
        self.value=value

       
>>> s=sy('hello world')
value = 'hello world'
>>> s
<__main__.sy object at>
>>> s.value
'hello world'
>>>
 

 总结:【1】@decorator后面不带括号时(也即装饰器无参数时),效果就相当于先定义func或cls,而后执行赋值操作func=decorator(func)或cls=decorator(cls);

【2】@decorator后面带括号时(也即装饰器有参数时),效果就相当于先定义func或cls,而后执行赋值操作 func=decorator(decoratorArgs)(func)或cls=decorator(decoratorArgs)(cls);

【3】如上将func或cls重新赋值后,此时的func或cls也不再是原来定义时的func或cls,而是一个可执行体,你只需要传入参数就可调用,func(args)=>返回值或者输出,cls(args)=>object of cls;

【4】最后通过赋值返回的执行体是多样的,可以是闭包,也可以是外部函数;当被装饰的是一个类时,还可以是类内部方法,函数;

【5】另外要想真正了解装饰器,一定要了解func.func_code.co_varnames,func.func_defaults,通过它们你可以以func的定义之外,还原func的参数列表;另外关键字参数是因为调用而出现的,而不是因为func的定义,func的定义中的用等号连接的只是有默认值的参数,它们并不一定会成为关键字参数,因为你仍然可以按照位置来传递它们。

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 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
1659
14
PHP Tutorial
1257
29
C# Tutorial
1231
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.

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.

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.

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.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

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.

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