【问题标题】:write a python decorator inside an abstract class and use it in an inherited class在抽象类中编写 python 装饰器并在继承类中使用它
【发布时间】:2022-01-03 01:06:41
【问题描述】:

TL;DR:我想在抽象类中运行一些逻辑(例如更新数据库)。也许还有另一种方法可以做到这一点,这就是我目前所能想到的(使用装饰器)

###################################

我有以下抽象类:

class MyAbstractClass(metaclass=abc.ABCMeta):

    @abc.abstractmethod
    def my_abstract_method(self, request):
        pass

    @staticmethod
    def decorator_func(self, func):
        def run_func(param_one, param_two):
            print('INSIDE run_func', param_one, param_two)
            results = self.update_database(param_one, param_two)
            func(test_id, request)
            print('FINISHED run_func')

        return run_func

    def update_database(self, param_one, param_two):
        results = <DO SOME BACKEND CALCULATIONS>
        return results

我想创建一个继承自该类的子类,并使用decorator_func 在抽象方法my_abstract_method 中进行一些数据库更新:

class ChildClass(MyAbstractClass):
    def __init__(self):
        super().__init__()

    @MyAbstractClass.decorator_func
    def my_abstract_method(self, request):
        get_data()

所以我知道my_abstract_method 将获得更新的数据,因为装饰器之前确保运行update_database

我尝试了很多组合(例如,删除 @staticmethod 或尝试使用 @classmethod 应用它)但它不起作用。对于当前代码,我收到错误:run_func() takes 2 positional arguments but 3 were given

关于如何在my_abstract_method 运行之前轻松运行update_database 有什么想法吗?

【问题讨论】:

    标签: python decorator abstract abstract-methods


    【解决方案1】:

    静态方法获取 一个 参数,即被修饰的函数。它返回的函数是需要一个参数来保存方法调用接收到的隐式实例参数的函数。

    @staticmethod
    def decorator_func(func):
        def run_func(self, param_one, param_two):
            print('INSIDE run_func', param_one, param_two)
            results = self.update_database(param_one, param_two)
            func(self, test_id, request)
            print('FINISHED run_func')
    
        return run_func
    

    因为func 是对函数 的引用,而不是绑定方法,所以您需要将self 作为第一个参数显式传递。

    【讨论】:

    • 感谢@chepner,您的解决方案有效。将自我移动到内部方法解决了我的问题
    猜你喜欢
    • 2015-02-07
    • 2011-03-23
    • 1970-01-01
    • 2013-09-26
    • 2021-10-24
    • 1970-01-01
    • 2012-10-28
    • 2021-12-10
    • 2019-12-07
    相关资源
    最近更新 更多