拥有一个中间类的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/