我有一个“抽象”类,例如:
class A:
def do_some_cool_stuff():
''' To override '''
pass
def do_some_boring_stuff():
return 2 + 2
B类,继承A:
class B(A):
def do_stuff()
return 4
有没有办法声明方法A.do_some_cool_stuff
必须被覆盖,并且可能在尝试创建B类对象时应该引发一些警告,当B有未实施A.do_some_cool_stuff
?
答案 0 :(得分:34)
是的,将A
定义为ABC (Abstract Base Class):
from abc import ABCMeta, abstractmethod
class A(object):
__metaclass__ = ABCMeta
@abstractmethod
def do_some_cool_stuff():
''' To override '''
pass
def do_some_boring_stuff():
return 2 + 2
您可以继承A
,但如果do_some_cool_stuff()
方法具有具体实现,则只能创建此类子类的实例:
>>> from abc import ABCMeta, abstractmethod
>>> class A(object):
... __metaclass__ = ABCMeta
... @abstractmethod
... def do_some_cool_stuff():
... ''' To override '''
... pass
... def do_some_boring_stuff():
... return 2 + 2
...
>>> class B(A):
... def do_stuff():
... return 4
...
>>> B()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class B with abstract methods do_some_cool_stuff