【问题标题】:Is it possible in Python to declare that method must be overridden?是否可以在 Python 中声明必须重写该方法?
【发布时间】:2013-06-28 11:09:40
【问题描述】:

我有一个“抽象”类,例如:

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?

【问题讨论】:

标签: python oop inheritance methods overriding


【解决方案1】:

是的,将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

【讨论】:

    猜你喜欢
    • 2019-07-01
    • 1970-01-01
    • 2014-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-13
    • 1970-01-01
    • 2012-08-10
    相关资源
    最近更新 更多