Skip to main content
 首页 » 编程设计

python之如何在可重写的类方法上使用装饰器

2024年12月31日7qq号

我有一个包含多个方法的自定义类,这些方法都返回一个代码。我想要标准逻辑来检查返回的代码是否符合该方法的可接受代码列表,如果不是预期的则引发错误。

我认为实现这一目标的一个好方法是使用装饰器:

from functools import wraps 
 
def expected_codes(codes): 
    def decorator(f): 
        @wraps(f) 
        def wrapper(*args, **kwargs): 
            code = f(*args, **kwargs) 
            if code not in codes: 
                raise Exception(f"{code} not allowed!") 
            else: 
                return code 
        return wrapper 
    return decorator 

然后我有一个像这样的类:

class MyClass: 
    @expected_codes(["200"]) 
    def return_200_code(self): 
        return "200" 
 
    @expected_codes(["300"]) 
    def return_300_code(self): 
        return "301" # Exception: 301 not allowed! 

这工作正常,但是如果我覆盖基类:

class MyNewClass: 
    @expected_codes(["300", "301"]) 
    def return_300_code(self): 
        return super().return_300_code()  # Exception: 301 not allowed! 

由于装饰器被覆盖,我本以为上面覆盖的方法会正确返回而不是引发异常。

从我通过阅读收集到的信息来看,我想要的方法不会起作用,因为装饰器是在类定义中评估的——但是我很惊讶没有办法实现我想要的。这一切都在 Django 应用程序的上下文中,我认为 Djangos method_decorator 装饰器可能已经为我解决了这个问题,但我认为我对它的工作原理存在根本性的误解。

请您参考如下方法:

长话短说

使用 __wrapped__ 属性忽略父级的装饰器:

class MyNewClass(MyClass): 
    @expected_codes(["300", "301"]) 
    def return_300_code(self): 
        return super().return_300_code.__wrapped__(self) # No exception raised 

解释

@decorator 语法等同于:

def f(): 
    pass 
f = decorator(f) 

因此你可以堆叠装饰器:

def decorator(f): 
    @wraps(f) 
    def wrapper(*args, **kwargs): 
        print(f"Calling {f.__name__}") 
        f(*args, **kwargs) 
    return wrapper 
 
@decorator 
def f(): 
    print("Hi!") 
 
@decorator 
def g(): 
    f()   
g() 
 
#Calling g 
#Calling f 
#Hi! 

但是如果你想避免堆叠,__wrapped__ 属性是你的 friend :

@decorator 
def g(): 
    f.__wrapped__() 
g() 
 
#Calling g 
#Hi! 

简而言之,如果您在子类的装饰方法中调用被装饰父类的方法之一,装饰器将堆叠在一起,而不是相互覆盖。

因此,当您调用 super().return_300_code() 时,您调用的是父类的装饰方法,它不接受 301 作为有效代码,并将提出自己的异常(exception)。

如果你想重用原始父类的方法,即只返回 301 而不检查的方法,你可以使用 __wrapped__ 属性,它可以访问原始函数(在装饰之前):

class MyNewClass(MyClass): 
    @expected_codes(["300", "301"]) 
    def return_300_code(self): 
        return super().return_300_code.__wrapped__(self) # No exception raised