Skip to main content
 首页 » 编程设计

Python成员函数装饰器使用实例作为参数

2025年05月04日13langtianya

如何在 python 成员函数装饰器中使用实例作为参数。 下面是一个例子。

def foo(func): 
    def wrap(s): 
        func() 
        s.ma() 
    return wrap 
 
class A: 
    def ma(self): 
        print "this is ma" 
 
    @foo(self)     #error.name 'self' is not defined 
    def mb(self): 
        print "this is mb" 

请您参考如下方法:

不清楚您在寻找什么,但是如果您希望能够在装饰器中使用对实例的引用:

def foo(func): 
    def wrap(s): # I'd call this 'self' instead of 's' to remind us it's a reference to an instance 
 
        func(s) # This is a function, not a method yet - so we need to pass in the reference 
 
        s.ma() # This is a method, because you use attribute lookup on the object s to get it 
    return wrap 
 
class A: 
    def ma(self): 
        print "this is ma" 
 
    @foo     # if the way foo wraps mb doesn't depend on some arg, don't use args here 
    def mb(self): 
        print "this is mb" 

我认为您在这里对 Python 中的方法和函数之间的区别感到困惑 – 您似乎期望 func 会像方法一样工作,但实际上它仍然是一个函数正在装修。装饰函数将在实例的属性查找中转换为方法;这意味着当您在包装函数中调用 func 时,您仍然需要显式 self。

查看 How to make a chain of function decorators? 的绝妙答案以便更好地解释正在发生的事情。