gpt4 book ai didi

python - 装饰类方法 - 如何将实例传递给装饰器?

转载 作者:IT老高 更新时间:2023-10-28 20:22:51 25 4
gpt4 key购买 nike

这是 Python 2.5,它是 GAE也一样,没关系。

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

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()

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

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

但我得到 TypeError: foo() 只需要 1 个参数(给定 0) 作为 .foo(),作为一个对象方法,需要 self 作为参数。我猜问题是当我执行装饰器代码时, bar 的实例实际上并不存在。

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

最佳答案

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

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 - 装饰类方法 - 如何将实例传递给装饰器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2365701/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com