python:仅覆盖抽象类中的一些方法

标签 python inheritance abc

拥有一个中间类的Python式方法是什么,该中间类会覆盖抽象父级中的一些方法,但不是全部。它是否还必须覆盖它不希望更改的方法?

class Animal(six.with_metaclass(ABCMeta, object)):):

    @abstractmethod
    def move(self):
        raise NotImplementedError()

    @abstractmethod
    def give_birth(self):
        raise NotImplementedError()

class Mammal(Animal):


   def move(self): # I want to inherit this method from Animal
        raise NotImplementedError()

    def give_birth(self):  # want to overwrite
        # not with eggs!



class Dog(Mammal):
    def move(self):
       return 'MOVED like a dog'

这段代码实际上并没有破坏,但我的 IDE (pycharm) 突出显示了“Mammal 类”并表示“必须实现所有抽象方法”。也许 Animal.move 不应该是抽象的?

最佳答案

您也可以将 Mammal 设为抽象类,并且不需要它来实现方法

from abc import ABC

class Animal(ABC):  # I've never used six, but your way of doing things should work here too
    @abstractmethod
    def move(self):
        raise NotImplementedError()    
    @abstractmethod
    def give_birth(self):
        raise NotImplementedError()

class Mammal(Animal, ABC):
    def give_birth(self):  # want to overwrite
        print("Live birth")

class Dog(Mammal):
    def move(self):
        print("Run in circles")

关于python:仅覆盖抽象类中的一些方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51710188/

相关文章:

C++:条件继承是否可能

带有抽象基类的 Python 类型提示

python-3.x - from collections import Container 和 from collections.abc import Container 之间的区别

python - 从PIL导入图像,ImageTk ImportError:无法导入名称ImageTk

python - 为给定的单词集创建 id 的简单 [pythonic] 方法

Python 不被解释而是显示编译行为

python - 使用UTF-8打开文件进行读取

c++ - clang/g++ 与私有(private)继承和使用声明的区别

Java List 如何设置和获取父类型列表的子对象