Abstract base class is not enforcing function implementation
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | from abc import abstractmethod, ABCMeta class AbstractBase(object): __metaclass__ = ABCMeta @abstractmethod def must_implement_this_method(self): raise NotImplementedError() class ConcreteClass(AbstractBase): def extra_function(self): print('hello') # def must_implement_this_method(self): # print("Concrete implementation") d = ConcreteClass() # no error d.extra_function() |
我在python 3.4上。我想定义一个抽象基类,它定义一些需要由它的子类实现的函数。但当子类不实现函数时,python不会引发notimplementederror…
在python 3中,元类声明的语法已经更改。而不是
1 2 3 4 5 6 | import abc class AbstractBase(metaclass=abc.ABCMeta): @abc.abstractmethod def must_implement_this_method(self): raise NotImplementedError() |
调用
1 2 | TypeError: Can't instantiate abstract class ConcreteClass with abstract methods must_implement_this_method |
号
希望这有帮助:)