python: 仅覆盖抽象类中的一些方法
python: Overwrite only some methods from AbstractClass
有什么 pythonic 方法可以让中间 class 覆盖抽象父类中的一些方法,但不是全部。它也必须覆盖它不想更改的方法吗?
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) 突出显示“class Mammal”并说“必须实现所有抽象方法”。也许 Animal.move
不应该是抽象的吗?
您也可以将 Mammal
设为抽象 class,并且不需要实现这些方法
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")
有什么 pythonic 方法可以让中间 class 覆盖抽象父类中的一些方法,但不是全部。它也必须覆盖它不想更改的方法吗?
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) 突出显示“class Mammal”并说“必须实现所有抽象方法”。也许 Animal.move
不应该是抽象的吗?
您也可以将 Mammal
设为抽象 class,并且不需要实现这些方法
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")