0
需要帮助。传递装饰器的功能
有一个文件with_class.py来保存类的装饰器的实现。该函数正在从另一个文件use_class.py中调用。
with_class.py
def __init__(self,f):
self.f = f
def __call__(self,x):
self.f(x)
@decorate
def foo(x):
print "inside foo" , x
use_class.py
import with_class
a = with_class.foo(x)
它工作正常。 现在,如果我想传递一个函数来代替x。 我有在with_class.py和use_class.py中定义的函数,我想传递给“a = with_class.foo(with_class.decorate.disp())”。 disp()是在类中定义的函数。现在上面的代码看起来像:
with_class.py
class decorate:
def __init__(self,f):
self.f = f
def __call__(self,g):
self.f(g)
def disp(self):
print "inside the display"
@decorate
def foo(fn):
print "inside foo"
fn()
use_class.py
import with_class
a = with_class.foo(with_class.decorate.disp())
我收到错误
"**TypeError: unbound method disp() must be called with decorate instance as first argument**".
是否有人可以帮助我找到哪里我错了。
在此先感谢。
...我如上试图与代码和它工作得很好。但我尝试使用另一个文件“use_class.py”,其中:import with_class –
import with_class with_class.foo(decorate.disp)它失败,错误...... NameError:name'decorate'未定义。 –
如果您在另一个名为with_class的文件中定义了'decorate',那么您需要将其引用为'with_class.decorate',否则请执行'from_class import decorate'。这就是Python的工作原理,与装饰器没有特别的关系。 –