Python 装饰器 使用总结

这个装饰器很像Java的注解....python

一级装饰器(不带参数)bash

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# time @2016/3/11 15:13 create by JasonYang


def decorate(func):
    def wrapper(*args, **kwargs):
        print "call function named %s" % func.__name__
        func(*args, **kwargs)

    return wrapper


@decorate
def test():
    print 'bob'

test()

运行结果:app

call function named test
bob

二级装饰器(带参数)spa

def decorate_2(param):
    def decorate_(func):
        def wrapper_(*args, **kwargs):
            print 'hello i am decorator 2', str(param)
            print "call function named %s" % func.__name__
            func(*args, **kwargs)
        return wrapper_
    return decorate_
@decorate_2('装饰器')
def f():
    print 'alice'

f()

运行结果:code

hello i am decorator 2 装饰器
call function named f
alice

将装饰器定义为类:utf-8

# -*- coding:utf-8 -*- 
# 2016/10/21
# mail:ybs.kakashi@gmail.com
"""
类装饰器
"""


class DecoratorClass:
    def __init__(self, func):
        self.func = func
        self.ncalls = 0

    def __call__(self, *args, **kwargs):
        self.ncalls += 1
        return self.func(*args, **kwargs)


@DecoratorClass
def add(a, b):
    return a + b


print "--", add.ncalls
print add(1, 2)
print "--", add.ncalls
print add(1, 3)
print "--", add.ncalls

结果:it

D:\Python27\python.exe E:/workspace/xx/decorator/test1.py
-- 0
3
-- 1
4
-- 2

Process finished with exit code 0
相关文章
相关标签/搜索