如何使用@abstractmethod创建一个抽象接口来指定其构造函数的参数结构?

2024-06-16 09:51:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我理解下面的代码为什么抛出和异常,以及一些避免异常的方法,但我不理解使用@abstractmethod来创建抽象接口的预期方法

我的目标是

  • 创建具有单参数构造函数的抽象接口Foo
  • 以及一个适配器类FooAdapter,它可以由打算实现Foo的类进行子类化

问题是,如果我在构造函数中添加对“super”的适当调用,我最终将调用abstractmethod并引发异常

  • 修正1。不要加超级。工作,但似乎是错误的,因为它可以删除其他类所需的信息,如果与其他类混合
  • 修正2。不要在界面中为init添加签名。这是可行的,但似乎是错误的,因为接口的关键是定义接口。我不会这么做,至少不会为了构造器

我觉得我想得不对。什么是Python的方式


from abc import ABC, abstractmethod

class Foo(ABC):
    @abstractmethod
    def __init__(self, my_arg):
        raise NotImplementedError


class FooAdapter(Foo):
    def __init__(self, my_arg):
        super().__init__()

根据下面的公认答案

您根本不需要使用NotImplementedError,只需使用“pass”。 如果子类未实现指定的方法,@abstractmethod机制将引发异常


Tags: 方法代码selffooinitmydef错误
1条回答
网友
1楼 · 发布于 2024-06-16 09:51:59

abc.abstarctmethod{a1}

Note: Unlike Java abstract methods, these abstract methods may have an implementation. This implementation can be called via the super() mechanism from the class that overrides it. This could be useful as an end-point for a super-call in a framework that uses cooperative multiple-inheritance.

因此,您只需要将存根放在不做任何事情的位置,而不是引发NotImlementedError

相关问题 更多 >