Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.2k views
in Technique[技术] by (71.8m points)

python - Must a class implement all abstract methods?

Suppose you have the following class:

class Base(object):
    def abstract_method(self):
        raise NotImplementedError

Can you then implement a inheriting class, which does not implement the abstract method? For example, when it does not need that specific method. Will that give problems or is it just bad practice?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you're implementing abstract methods the way you show, there's nothing enforcing the abstractness of the class as a whole, only of the methods that don't have a concrete definition. So you can create an instance of Base, not only of its subclasses.

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

However, if you use the abc module from the standard library to designate abstract methods, it will not allow you to instantiate an instance of any class that does not have a concrete implementation of any abstract methods it has inherited. You can leave inherited abstract methods unimplemented in an intermediate abstract base class (e.g. a subclass of the original base, that is itself intended to still be abstract), but you can't make any instances.

Here's what using abc looks like:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...