编程语言
首页 > 编程语言> > python-使具体类抽象,保留构造函数

python-使具体类抽象,保留构造函数

作者:互联网

假设您有一个具体的课程

class Knight(object):
    def __init__(self, name):
        self._name = name
    def __str__(self):
        return "Sir {} of Camelot".format(self.name)

现在,发生了类层次结构必须更改的情况.骑士应该成为一个抽象的基类,为各种城堡的骑士提供一堆具体的子类.很简单:

class Knight(metaclass=ABCMeta):  # Python 3 syntax
    def __str__(self):
        return "Sir {} of {}".format(self.name, self.castle)
    @abstractmethod
    def sing():
        pass

class KnightOfTheRoundTable(Knight):
    def __init__(self, name):
        self.name = name
    @property
    def castle(self):
        return "Camelot"
    @staticmethod
    def sing():
        return ["We're knights of the round table",
                "We dance whenever we're able"]

但是现在所有使用Knight(“ Galahad”)构造Knight的代码都被破坏了.相反,我们可以保持Knight不变,并引入一个BaseKnight,但是随后可能需要更改检查isinstance(x,Knight)并在任何骑士上都可以使用的代码来代替,以检查BaseKnight.

如何将一个具体的类变成一个抽象的类,同时保留构造函数和isinstance检查?

解决方法:

使现有类成为基类,但是在尝试实例化基类时将overload __new__返回一个子类:

class Knight(metaclass=ABCMeta):
    def __new__(cls, *args, **kwargs):
        if cls is Knight:
            # attempt to construct base class, defer to default subclass
            return KnightOfTheRoundTable(*args, **kwargs)
        else:
            obj = super(Knight, cls).__new__(cls)
            obj.__init__(*args, **kwargs)
            return obj
    def __str__(self):
        return "Sir {} of {}".format(self.name, self.castle)
    @abstractmethod
    def sing():
        pass

现在Knight(“ Galahad”)继续工作,但返回KnightOfTheRoundTable. isinstance(Knight(“ Robin”),Knight)返回True,就像对其他任何子类实例进行isinstance(x,Knight)检查一样.

标签:oop,inheritance,abstract-class,python
来源: https://codeday.me/bug/20191029/1956968.html