python - 在 Python 中是否可以声明必须重写该方法?

标签 python oop inheritance methods overriding

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

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 时?

最佳答案

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

关于python - 在 Python 中是否可以声明必须重写该方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17402622/

相关文章:

python - 无法在 Python 中显示 TreeView

Python Dataframe 到 Hana 表

javascript - 如何仅传入属性来实例化 JavaScript 对象?

Swift 类型和良好的旧时尚分层单一继承

python - 如何添加到从另一个类继承的 python 类的初始定义?

python - 正则表达式:将 "white space"字符和 - 字符更改为空

python - 如何识别Python中不可打印的unicode字符

java - 只有一种实现的接口(interface)

java - 多态性:方法改变,但参数值不变

java - 处理传递 String 变量时出现 NullPointerException