首页 > 解决方案 > 在父类方法上使用子类中指定的装饰器

问题描述

假设我有两个类ChildParent(这是 的基类Child)。我有另一个类Dec,它包含一个dec我想在Parent方法上使用的装饰器。我希望能够指定一个Dec应该在Child.

这是我到目前为止所尝试的:

class Dec():
    def dec(self, func):
        def wrapper(self):
            print("Before func call")
            func(self)
            print("After func call")

        return wrapper

class Parent():
    dec = None

    @dec.dec
    def p(self):
        print('hello')

dec = Dec()

class Child(Parent):
    a = dec

t = Child()
t.p()

所以,我得到了

AttributeError: 'NoneType' object has no attribute 'dec'

@dec.dec.

是否有任何选项可以指定一个应该在课堂上使用的带有装饰器的Child类?

标签: python

解决方案


您在这里遇到的问题与范围界定有关。

当我运行这段代码时,我收到了这个错误:

...<stack trace>...
  File ".\__main__.py", line 10, in <module>
    class Parent():
  File ".\__main__.py", line 13, in Parent
    @dec.dec
AttributeError: 'NoneType' object has no attribute 'dec'

使用它,您可以看到您有一些范围问题。在此文件中,您定义dec了多次。不要像第 11 行那样实例化,而是Dec定义Dec.dec(...)为 a @classmethod,可从类本身调用,而不仅仅是类的实例。

这是一个潜在的解决方案:

class Dec():
    @classmethod
    def dec(self, func):
        def wrapper(self):
            print("Before func call")
            func(self)
            print("After func call")

        return wrapper

class Parent():
    @Dec.dec
    def p(self):
        print('hello')


class Child(Parent):
    pass # you didn't really need anything here.

t = Child()
t.p()

这提供了我认为是预期的行为:

Before func call
hello
After func call

推荐阅读