【问题标题】:Overwrite methods but keep decorator (python)覆盖方法但保留装饰器(python)
【发布时间】:2021-08-12 09:11:28
【问题描述】:

我有一个类和一个子类,并想从框架 prefect.io 继承一个带有装饰器 @task 的方法。

代码示例:

@task
def test1(self):
     pass

子类

def test2(self):
     print("succeed")

但是现在方法 test2 不再有装饰器 @task 了。我不能在子类中声明 @task。我是否可以覆盖该方法但保留 @task

【问题讨论】:

  • 为什么不直接将任务导入作用域,以便子类可以装饰其方法?
  • “我不能在子类中声明@task。”为什么你不能?
  • “我是否可以覆盖该方法但保留@task”这是不可能的,您最终将不得不再次装饰生成的方法以某种方式。跨度>
  • 好的@juanpa.arrivillaga,感谢您的回答,这是不可能的。

标签: python methods overwrite prefect


【解决方案1】:

我通常会推荐类似的东西

class Base:
    @task
    def test1(self):
        return self.test1_impl()

    def test1_impl(self):
        ...


class Child:
    def test1_impl(self):
        ...

现在Child 的工作不是重写修饰函数,而是重写继承的修饰函数使用的未修饰函数

【讨论】:

    【解决方案2】:

    为什么不再导入任务?

    from prefect import task
    

    【讨论】:

      猜你喜欢
      • 2022-09-29
      • 2014-10-08
      • 2021-10-04
      • 2021-02-04
      • 1970-01-01
      • 2013-01-19
      • 2017-07-12
      • 2017-03-18
      • 1970-01-01
      相关资源
      最近更新 更多