类必须实现所有抽象方法吗?

Jan*_*lem 3 python oop class

假设您有以下课程:

class Base(object):
    def abstract_method(self):
        raise NotImplementedError
Run Code Online (Sandbox Code Playgroud)

那么你能实现一个不实现抽象方法的继承类吗?例如,当它不需要那个特定方法时。这会带来问题还是只是不好的做法?

Blc*_*ght 5

如果您按照所示方式实现抽象方法,则没有任何东西可以强制整个类的抽象性,只有没有具体定义的方法。因此,您可以创建 的实例Base,而不仅仅是其子类的实例。

b = Base() # this works following your code, only b.abstract_method() raises

def Derived(Base):
    ... # no concrete implementation of abstract_method, so this class works the same
Run Code Online (Sandbox Code Playgroud)

但是,如果您使用标准库中的模块abc来指定抽象方法,则它将不允许您实例化任何没有继承的任何抽象方法的具体实现的类的实例可以在中间抽象基类(例如原始基类的子类,其本身仍然是抽象的)中保留未实现的继承抽象方法,但您不能创建任何实例。

这是使用的abc样子:

from abc import ABCMeta, abstractmethod

class ABCBase(metaclass=ABCMeta):
    @abstractmethod
    def abstract_method(self, arg):
        ...

class ABCDerived(ABCBase):
    ... # we don't implement abstract_method here, so we're also an abstract class
    
d = ABCDerived() # raises an error
Run Code Online (Sandbox Code Playgroud)