简体   繁体   中英

python: Overwrite only some methods from AbstractClass

What is the pythonic way to have an intermediate class that overwrites some of the method's from an Abstract parent, but not all. Must it also overwrite methods it does not wish to change?

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'

This code doesn't actually break, but my IDE (pycharm) highlights “class Mammal” and says “must implement all abstract methods". Maybe Animal.move shouldn't be abstract?

You can make Mammal an abstract class as well, and it will not be required to implement the methods

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM