带有自参数的类方法装饰器? [英] Class method decorator with self arguments?

查看:46
本文介绍了带有自参数的类方法装饰器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将类字段作为参数传递给类方法上的装饰器?我想做的是:

How do I pass a class field to a decorator on a class method as an argument? What I want to do is something like:

class Client(object):
    def __init__(self, url):
        self.url = url

    @check_authorization("some_attr", self.url)
    def get(self):
        do_work()

它抱怨 self 不存在用于将 self.url 传递给装饰器.有没有办法解决这个问题?

It complains that self does not exist for passing self.url to the decorator. Is there a way around this?

推荐答案

是的.不是在类定义时传入实例属性,而是在运行时检查它:

Yes. Instead of passing in the instance attribute at class definition time, check it at runtime:

def check_authorization(f):
    def wrapper(*args):
        print args[0].url
        return f(*args)
    return wrapper

class Client(object):
    def __init__(self, url):
        self.url = url

    @check_authorization
    def get(self):
        print 'get'

>>> Client('http://www.google.com').get()
http://www.google.com
get

装饰器拦截方法参数;第一个参数是实例,因此它从中读取属性.您可以将属性名称作为字符串传递给装饰器并使用 getattr 如果您不想对属性名称进行硬编码:

The decorator intercepts the method arguments; the first argument is the instance, so it reads the attribute off of that. You can pass in the attribute name as a string to the decorator and use getattr if you don't want to hardcode the attribute name:

def check_authorization(attribute):
    def _check_authorization(f):
        def wrapper(self, *args):
            print getattr(self, attribute)
            return f(self, *args)
        return wrapper
    return _check_authorization

这篇关于带有自参数的类方法装饰器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆