装饰 Python 类方法 - 如何将实例传递给装饰器? [英] Decorating Python class methods - how do I pass the instance to the decorator?

查看:64
本文介绍了装饰 Python 类方法 - 如何将实例传递给装饰器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是 Python 2.5,它也是 GAE,但这并不重要.

This is Python 2.5, and it's GAE too, not that it matters.

我有以下代码.我正在装饰 bar 中的 foo() 方法,使用 dec_check 类作为装饰器.

I have the following code. I'm decorating the foo() method in bar, using the dec_check class as a decorator.

class dec_check(object):

  def __init__(self, f):
    self.func = f

  def __call__(self):
    print 'In dec_check.__init__()'
    self.func()

class bar(object):

  @dec_check
  def foo(self):
    print 'In bar.foo()'

b = bar()
b.foo()

执行此操作时,我希望看到:

When executing this I was hoping to see:

In dec_check.__init__()
In bar.foo()

但是我得到TypeError: foo() requires just 1 argument (0 given)"作为.foo(),作为一个对象方法,需要自我作为论据.我猜问题是当我执行装饰器代码时 bar 的实例实际上并不存在.

But I'm getting "TypeError: foo() takes exactly 1 argument (0 given)" as .foo(), being an object method, takes self as an argument. I'm guessing problem is that the instance of bar doesn't actually exist when I'm executing the decorator code.

那么如何将 bar 的实例传递给装饰器类?

So how do I pass an instance of bar to the decorator class?

推荐答案

你需要把装饰器做成descriptor -- 通过确保其(元)类具有 __get__ 方法,或者 方式 更简单,通过使用装饰器 function 而不是装饰器 class (因为函数已经是描述符).例如:

You need to make the decorator into a descriptor -- either by ensuring its (meta)class has a __get__ method, or, way simpler, by using a decorator function instead of a decorator class (since functions are already descriptors). E.g.:

def dec_check(f):
  def deco(self):
    print 'In deco'
    f(self)
  return deco

class bar(object):
  @dec_check
  def foo(self):
    print 'in bar.foo'

b = bar()
b.foo()

这个打印

In deco
in bar.foo

根据需要.

这篇关于装饰 Python 类方法 - 如何将实例传递给装饰器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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