如何在Python中使用类实例变量作为方法装饰器的参数? [英] How can I use a class instance variable as an argument for a method decorator in Python?

查看:316
本文介绍了如何在Python中使用类实例变量作为方法装饰器的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Python中使用类实例变量作为方法装饰器的参数?
下面是一个最小的示例,显示了我正在尝试执行的操作。由于装饰器函数无法访问该实例的引用,并且我不知道如何从装饰器访问该引用,因此它显然失败了。

How can I use a class instance variable as an argument for a method decorator in Python? The following is a minimal example shows what I'm trying to do. It obviously fails as the decorator function does not have access to the reference to the instance and I have no idea how to get access to the reference from the decorator.

def decorator1(arg1):
    def wrapper(function):
        print "decorator argument: %s" % arg1
        return function
    return wrapper

class Foo(object):
    def __init__(self, arg1):
        self.var1 = arg1

    @decorator1(self.var1)
    def method1(self):
        print "method1"

foo = Foo("abc")
foo.method1()


推荐答案

这是行不通的。装饰器是在创建类的时间内调用的,该时间要比创建实例早得多( if 曾经发生过)。因此,如果您的装饰器需要实例,则必须在实例化时进行装饰:

It's not going to work; the decorator is called during class creation time, which is long before an instance is created (if that ever happens). So if your "decorator" needs the instance, you have to do the "decorating" at instantiation time:

def get_decorator(arg1):
    def my_decorator(function):
        print "get_decorator argument: %s" % arg1
        return function
    return my_decorator

class Foo(object):
    def __init__(self, arg1):
        self.var1 = arg1
        self.method1 = get_decorator(self.var1)(self.method1)

    def method1(self):
        print "method1"

foo = Foo("abc")
foo.method1()

请注意,我根据它们的含义更改了功能名称;实际的装饰器(即(可能)修改该方法的函数)在您的情况下是包装器,而不是 decorator1

Note that I changed the function names according to their meanings; the actual "decorator", i.e. the function that (potentially) modifies the method, is wrapper in your case, not decorator1.

这篇关于如何在Python中使用类实例变量作为方法装饰器的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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