我有一个定义了几个空方法的基类。我想强制/强制在子类中定义这些方法,并在初始化时使它崩溃,以防它们被覆盖。
例如:
class Shape:
def __init__(self, name):
self.name = name
def number_of_edges(self):
pass # method HAS TO be overloaded in subclass
class Triangle(Shape):
def __init__(self, name):
super(Triangle, self).__init__()
def number_of_edges(self):
return 3
似乎Python
方式是提出NotImplementedError
:
def number_of_edges(self):
raise(NotImplementedError)
但是,在类实例化期间提前崩溃并检测缺少实现可能是有益的。为什么这不是默认值,可以这样做吗?
答案 0 :(得分:2)
使用abc
module创建一个抽象基类。
import abc
class Shape(object):
__metaclass__ = abc.ABCMeta
def __init__(self, name):
self.name = name
@abc.abstractmethod
def number_of_edges(self):
pass
使用@abc.abstractmethod
decorator修饰的任何方法都会触发TypeError
例外:
>>> import abc
>>> class Shape(object):
... __metaclass__ = abc.ABCMeta
... def __init__(self, name):
... self.name = name
... @abc.abstractmethod
... def number_of_edges(self):
... pass
...
>>>
>>> class Triangle(Shape):
... pass
...
>>> Triangle('t3')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class Triangle with abstract methods number_of_edges
>>> class Triangle(Shape):
... def number_of_edges(self):
... return 3
...
>>> Triangle('t3')
<__main__.Triangle object at 0x105f3b8d0>
答案 1 :(得分:1)
您可以使用Abstract Base Class;
import abc
class Shape:
__metaclass__ = abc.ABCMeta
def __init__(self, name):
self.name = name
@abc.abstractmethod
def number_of_edges(self):
pass # method HAS TO be overloaded in subclass
现在,如果Triangle类没有覆盖number_of_edges
方法,它将引发异常。