假设你有一个具体的类制作一个具体的类抽象,保留构造
class Knight(object):
def __init__(self, name):
self._name = name
def __str__(self):
return "Sir {} of Camelot".format(self.name)
现在它发生的类层次结构必须改变。 Knight
应该成为一个抽象基类,并为各城堡的骑士提供一堆具体的子类。很容易:
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
检查?
+1为另一个有效的解决方案,但我不明白为什么从'Knight .__ new__'返回'Knight'的子类是如此可怕。毕竟,一个子类实例*是一个'Knight',对吧?有什么地方可能会出现错误吗? – 2014-10-21 06:50:13
我不得不改变一些事情来修复我忽略的错误。现在并没有更好的方法,但我确实给了这个方法两个好处。 – Veedrac 2014-10-21 13:10:50