【问题标题】:python: Overwrite only some methods from AbstractClasspython:仅覆盖抽象类中的一些方法
【发布时间】:2018-08-06 14:41:25
【问题描述】:

拥有一个覆盖抽象父类的一些方法的中间类的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) 突出显示“类 Mammal”并说“必须实现所有抽象方法”。也许 Animal.move 不应该是抽象的?

【问题讨论】:

  • 您想从Animal 继承move,但它是一个抽象方法,因此它在Animal 中没有实现。如果你想像你说的那样继承它,你必须具体实现Animal.move(即不是abstractmethod)。究竟是什么让您感到困惑?
  • 不幸的是,我不得不用相同的代码替换 Animal.get_move。认为可能有更好的方法。
  • 我不明白,Animal.get_move 是什么?什么相同的代码,我没有看到任何代码重复?为什么这个解决方案不能令人满意?能说清楚一点吗?
  • 我想我会忽略 IDE 警告。哺乳动物本质上也是一个抽象类。
  • 对不起。我编辑了问题以反映我只想实现 Dog.move,而不是 Mammal.move。我认为解决方案是删除Animal.move定义上方的装饰器

标签: python inheritance abc


【解决方案1】:

您也可以将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")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-02
    • 2012-04-12
    • 1970-01-01
    • 2014-06-20
    相关资源
    最近更新 更多