关于python的装饰器

1.基础讲解,参考:点击打开链接

2.常见的装饰器模式包括(主要应用):

a.参数检查;

b.缓存;

c.代理;

d.上下文提供者;

a.参数检查

检查接收或返回的参数

# _*_ coding=utf-8 _*_
# __author__ = 'lucas'
from itertools import izip
rpc_info = {}


def xmlrpc(in_=(), out=(type(None),)):
    def _xmlrpc(function):
        func_name = function.func_name
        rpc_info[func_name] = (in_, out)
        print "func_name is %s" % func_name
        print rpc_info

        def _check_types(elements, types):
            if len(elements) != len(types):
                raise TypeError('argument count is wrong')
            # print "this is %s %s" % (elements,types)
            typed = enumerate(izip(elements, types))
            for index, couple in typed:
                arg, of_the_right_type = couple
                if isinstance(arg, of_the_right_type):
                    continue
                raise TypeError('arg #%d should be %s' % (index, of_the_right_type))

        def __xmlrpc(*args):
            checkable_args = args[1:]
            # print "that is %s %s" %(checkable_args,checkable_args[1:])
            _check_types(checkable_args, in_)
            res = function(*args)
            if not type(res) in (tuple, list):
                checkable_res = (res,)
            else:
                checkable_res = res
            _check_types(checkable_res, out)
            return res
        return __xmlrpc
    return _xmlrpc


class RPCView(object):
    @xmlrpc((int, int))
    def meth1(self, int1, int2):
        print 'received %d and %d' % (int1, int2)

    @xmlrpc((str,), (int,))
    def meth2(self, phrase):
        print 'received %s' % phrase
        return 12
print rpc_info
my = RPCView()
my.meth1(1, 2)
my.meth2("2")
b.缓存(暂无)

c.代理

class User(object):
    def __init__(self, roles):
        self.roles = roles


class Unauthorized(Exception):
    pass


def protect(role):
    def _protect(function):
        def __protect(*args, **kw):
            user = globals().get('user')
            print user
            print user.roles
            if user is None or role not in user.roles:
                raise Unauthorized("I won't tell you")
            return function(*args, **kw)
        return __protect
    return _protect


tarek = User(('admin', 'user', 'commonuser'))
bill = User(('user', ))


class MySecrets(object):
    @protect('admin')
    def waffle_recipe(self):
        print 'use tons of butter!'

these_are = MySecrets()
user = bill
these_are.waffle_recipe()
user = bill
these_are.waffle_recipe()
d.上下文提供者(暂无)


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值