更新继承自抽象 类 的 类

Updating Classes that inherit from abstract classes

我有一个摘要classship

from abc import ABC, abstractmethod
class ship(ABC):
    def __init__(self):
         ...

    @abstractmethod
    def do_stuff(self,stuff,things):
         pass

我有多个 class 继承自它(destroyercruiserpatrol_boat 等...)

class carrier(ship):
    def __init__(self):
         ....
    def do_stuff(self,stuff,things):
         ....

目前,如果我要添加,假设 def do_more_stuff(self):ship

class ship(ABC):
    def __init__(self):
         ...

    @abstractmethod
    def do_stuff(self,stuff,things):
         pass

    @abstractmethod
    def do_more_stuff(self,stuff,things):
        pass

在我将它们重新输入到控制台之前,更改不会影响任何子classes。我该如何更改?

如果你真的从头开始重新定义一个class,它就是一个不同的class; subclasses 仍然继承自 ship 的旧版本。您不能只定义一个名为 ship 的新 class 并期望子 class 能够神奇地找到它。

通常情况下,如果您想在创建后对 ship 进行猴子修补以添加新方法,您可以这样做:

def do_more_stuff(self,stuff,things):
    pass
ship.do_more_stuff = do_more_stuff

但不幸的是,abstractmethods for ABCs are an explicit exception to this rule:

Dynamically adding abstract methods to a class, or attempting to modify the abstraction status of a method or class once it is created, are not supported.

您必须预先完全定义抽象基 class,或者如果要向基 class 添加新的抽象方法,则稍后重新定义整个 class 层次结构。