装饰抽象方法

问题描述

我正在尝试在抽象类中装饰一个 @abstractmethod(在 Python 3.9 中由 abc.ABC 继承)

作为 MWE,

from abc import ABC,abstractmethod

class Block(ABC):

    def __init__(self,id=1):
        self.id=id

    @abstractmethod # the method I want to decorate
    def run(self):
        pass

    def store_id(self,fun): # the decorator I want to apply to run()
        def wrapper(fun):
            id=fun()
            self.id=id
            return id
        return wrapper

class Example(Block):

    def __init__(self,*args,**kwargs):
        super().__init__(*args,**kwargs)

    def run(self):
        print("I am running")
        id=3
        return id

t=Example()
t.run()
print(t.id)

我想修饰 run() 以便返回的 id 可以存储在对象中,而无需最终用户对其进行硬编码。

我正在寻找这个问题的解决方案,最完整的是this one

__init_subclass__ 魔术方法似乎是我在 store_id 中使用 Block 方法在具体实现后装饰 run() 的最佳镜头。

但是,如果我像这样覆盖 __init_subclass__ 中的 Block

def __init_subclass__(self):
        super().__init_subclass__()
        self.run = self.store_id(self.run)

我收到一个TypeError,但不知道如何解决TypeError: store_id() missing 1 required positional argument: 'fun'

我是否以正确的方式解决了这个问题?我是否遗漏了一些基本的 a 或与“abc”类型的类有关的东西?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)