如何在Python中使类或方法抽象?
我尝试像这样重新定义__new__():
class F:
def __new__(cls):
raise Exception("Unable to create an instance of abstract class %s" %cls)
但是现在,如果我创建一个从F继承的类G,像这样:
class G(F):
pass
然后,我也不能实例化G,因为它调用它的超类的__new__方法。
是否有更好的方法来定义抽象类?
只是对@TimGilbert老派回答的一个快速补充…你可以让你的抽象基类的init()方法抛出一个异常,这将阻止它被实例化,不是吗?
>>> class Abstract(object):
... def __init__(self):
... raise NotImplementedError("You can't instantiate this class!")
...
>>> a = Abstract()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in __init__
NotImplementedError: You can't instantiate this class!