Skip to main content
 首页 » 编程设计

Python之将类作为参数传递给该类中方法的装饰器

2025年02月15日8cmt

我想做以下事情:

class A(object): 
    def first_method(self): 
        print "I'm the first method!"     
 
    @some_decorator(A.first_method) 
    def second_method(self): 
        print "I'm the second method!" 

但是我遇到了一个问题,即在解析装饰器时 A 本身是未定义的。我有什么办法可以在装饰器中引用 A 吗?或者,如果我只是将绑定(bind)方法 first_method 传递给装饰器,我是否有可能恢复 first_method 属于 A?

请您参考如下方法:

在 python 3 中,你可以只说 @some_decorator(first_method),它会起作用,因为所有方法都是作为容器的类中的普通函数。

在 python 2 中,有一个由绑定(bind)和未绑定(bind)、实例、类和静态方法组成的复杂系统。因此,您无法在类定义内访问 first_method(直到类完全形成)。

一个小的解决方法是将该类分成两个类:

class BaseA(object): 
    def first_method(self): 
        print "I'm the first method!"     
 
class A(BaseA): 
    @some_decorator(BaseA.first_method) 
    def second_method(self): 
        print "I'm the second method!" 

并非适用于所有情况的最佳解决方案,但会奏效。


此外,请记住,在这两种情况下(py2 和 py3),装饰器将引用此处声明的 first_method。如果任何后代类重新定义了该方法,装饰器将不会使用新方法;只会使用父级。

您可能根本不应该引用 first_method。相反,只需在装饰器的包装器中接受 self/cls 第一个位置参数,并使用 self.first_method/cls.first_method那里:

import functools 
 
def some_decorator(fn): 
    @functools.wraps(fn) 
    def wrapper(self, *args, **kwargs): 
        first_method = self.first_method 
        first_method() 
        return fn(self, *args, **kwargs) 
    return wrapper 
 
class A(object): 
    def first_method(self): 
        print "I'm the first method of A!"     
 
    @some_decorator 
    def second_method(self): 
        print "I'm the second method!" 
 
 
class B(A): 
    def first_method(self): 
        print "I'm the first method of B!"     
 
 
A().second_method() 
# I'm the first method of A! 
# I'm the second method! 
 
B().second_method() 
# I'm the first method of B! 
# I'm the second method! 

如果你想使该方法可配置:

def some_decorator(method_name): 
    def decorator(fn): 
        @functools.wraps(fn) 
        def wrapper(self, *args, **kwargs): 
            first_method = getattr(self, method_name) 
            first_method() 
            return fn(self, *args, **kwargs) 
        return wrapper 
    return decorator 
 
 
class A(object): 
    def first_method(self): 
        print "I'm the first method of A!"     
 
    @some_decorator('first_method') 
    def second_method(self): 
        print "I'm the second method!" 
 
class B(A): 
    def first_method(self): 
        print "I'm the first method of B!"