拥有一个中间类来覆盖来自Abstract父级(而不是全部)的方法的pythonic方法是什么?是否还必须覆盖不希望更改的方法?
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)突出显示了“哺乳动物类”,并说“必须实现所有抽象方法”。也许Animal.move
不应该是抽象的吗?
答案 0 :(得分:3)
您也可以使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")