【问题标题】:Pure virtual methods in PythonPython中的纯虚方法
【发布时间】:2014-03-03 20:47:51
【问题描述】:

在Python中实现纯虚方法的思想正确的方法是什么?

只是在方法中提高NotImplementedError

或者有没有更好的方法?

谢谢!

【问题讨论】:

    标签: python oop inheritance virtual-functions


    【解决方案1】:

    虽然看到people using NotImplementedError 并不少见,但有些人会争辩说,“正确”的做法(从python 2.6 开始)是通过abc module 使用抽象基类

    from abc import ABCMeta, abstractmethod
    
    class MyAbstractClass(object):
        __metaclass__=ABCMeta
        @abstractmethod
        def my_abstract_method():
            pass
    

    与使用NotImplementedError 相比,使用abc 有两个主要(潜在)优势。

    首先,您将无法实例化抽象类(无需__init__ hacks):

    >>> MyAbstractClass()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: Can't instantiate abstract class MyAbstractClass with abstract methods my_abstract_method
    

    其次,您将无法实例化任何未实现所有抽象方法的子类:

    >>> class MyConcreteClass(MyAbstractClass):
    ...     pass
    ... 
    >>> MyConcreteClass()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: Can't instantiate abstract class MyConcreteClass with abstract methods my_abstract_method
    

    Here's a more complete overview on abstract base classes

    【讨论】:

      猜你喜欢
      • 2011-06-24
      • 2011-09-08
      • 2017-05-24
      • 2011-01-11
      • 2013-03-24
      • 1970-01-01
      • 2016-10-14
      • 2011-01-17
      相关资源
      最近更新 更多