/Doc/library/abc.rst

http://unladen-swallow.googlecode.com/ · ReStructuredText · 196 lines · 142 code · 54 blank · 0 comment · 0 complexity · dd48b173b057d159de1a677900826603 MD5 · raw file

  1. :mod:`abc` --- Abstract Base Classes
  2. ====================================
  3. .. module:: abc
  4. :synopsis: Abstract base classes according to PEP 3119.
  5. .. moduleauthor:: Guido van Rossum
  6. .. sectionauthor:: Georg Brandl
  7. .. much of the content adapted from docstrings
  8. .. versionadded:: 2.6
  9. This module provides the infrastructure for defining an :term:`abstract base
  10. class` (ABCs) in Python, as outlined in :pep:`3119`; see the PEP for why this
  11. was added to Python. (See also :pep:`3141` and the :mod:`numbers` module
  12. regarding a type hierarchy for numbers based on ABCs.)
  13. The :mod:`collections` module has some concrete classes that derive from
  14. ABCs; these can, of course, be further derived. In addition the
  15. :mod:`collections` module has some ABCs that can be used to test whether
  16. a class or instance provides a particular interface, for example, is it
  17. hashable or a mapping.
  18. This module provides the following class:
  19. .. class:: ABCMeta
  20. Metaclass for defining Abstract Base Classes (ABCs).
  21. Use this metaclass to create an ABC. An ABC can be subclassed directly, and
  22. then acts as a mix-in class. You can also register unrelated concrete
  23. classes (even built-in classes) and unrelated ABCs as "virtual subclasses" --
  24. these and their descendants will be considered subclasses of the registering
  25. ABC by the built-in :func:`issubclass` function, but the registering ABC
  26. won't show up in their MRO (Method Resolution Order) nor will method
  27. implementations defined by the registering ABC be callable (not even via
  28. :func:`super`). [#]_
  29. Classes created with a metaclass of :class:`ABCMeta` have the following method:
  30. .. method:: register(subclass)
  31. Register *subclass* as a "virtual subclass" of this ABC. For
  32. example::
  33. from abc import ABCMeta
  34. class MyABC:
  35. __metaclass__ = ABCMeta
  36. MyABC.register(tuple)
  37. assert issubclass(tuple, MyABC)
  38. assert isinstance((), MyABC)
  39. You can also override this method in an abstract base class:
  40. .. method:: __subclasshook__(subclass)
  41. (Must be defined as a class method.)
  42. Check whether *subclass* is considered a subclass of this ABC. This means
  43. that you can customize the behavior of ``issubclass`` further without the
  44. need to call :meth:`register` on every class you want to consider a
  45. subclass of the ABC. (This class method is called from the
  46. :meth:`__subclasscheck__` method of the ABC.)
  47. This method should return ``True``, ``False`` or ``NotImplemented``. If
  48. it returns ``True``, the *subclass* is considered a subclass of this ABC.
  49. If it returns ``False``, the *subclass* is not considered a subclass of
  50. this ABC, even if it would normally be one. If it returns
  51. ``NotImplemented``, the subclass check is continued with the usual
  52. mechanism.
  53. .. XXX explain the "usual mechanism"
  54. For a demonstration of these concepts, look at this example ABC definition::
  55. class Foo(object):
  56. def __getitem__(self, index):
  57. ...
  58. def __len__(self):
  59. ...
  60. def get_iterator(self):
  61. return iter(self)
  62. class MyIterable:
  63. __metaclass__ = ABCMeta
  64. @abstractmethod
  65. def __iter__(self):
  66. while False:
  67. yield None
  68. def get_iterator(self):
  69. return self.__iter__()
  70. @classmethod
  71. def __subclasshook__(cls, C):
  72. if cls is MyIterable:
  73. if any("__iter__" in B.__dict__ for B in C.__mro__):
  74. return True
  75. return NotImplemented
  76. MyIterable.register(Foo)
  77. The ABC ``MyIterable`` defines the standard iterable method,
  78. :meth:`__iter__`, as an abstract method. The implementation given here can
  79. still be called from subclasses. The :meth:`get_iterator` method is also
  80. part of the ``MyIterable`` abstract base class, but it does not have to be
  81. overridden in non-abstract derived classes.
  82. The :meth:`__subclasshook__` class method defined here says that any class
  83. that has an :meth:`__iter__` method in its :attr:`__dict__` (or in that of
  84. one of its base classes, accessed via the :attr:`__mro__` list) is
  85. considered a ``MyIterable`` too.
  86. Finally, the last line makes ``Foo`` a virtual subclass of ``MyIterable``,
  87. even though it does not define an :meth:`__iter__` method (it uses the
  88. old-style iterable protocol, defined in terms of :meth:`__len__` and
  89. :meth:`__getitem__`). Note that this will not make ``get_iterator``
  90. available as a method of ``Foo``, so it is provided separately.
  91. It also provides the following decorators:
  92. .. function:: abstractmethod(function)
  93. A decorator indicating abstract methods.
  94. Using this decorator requires that the class's metaclass is :class:`ABCMeta` or
  95. is derived from it.
  96. A class that has a metaclass derived from :class:`ABCMeta`
  97. cannot be instantiated unless all of its abstract methods and
  98. properties are overridden.
  99. The abstract methods can be called using any of the normal 'super' call
  100. mechanisms.
  101. Dynamically adding abstract methods to a class, or attempting to modify the
  102. abstraction status of a method or class once it is created, are not
  103. supported. The :func:`abstractmethod` only affects subclasses derived using
  104. regular inheritance; "virtual subclasses" registered with the ABC's
  105. :meth:`register` method are not affected.
  106. Usage::
  107. class C:
  108. __metaclass__ = ABCMeta
  109. @abstractmethod
  110. def my_abstract_method(self, ...):
  111. ...
  112. .. note::
  113. Unlike Java abstract methods, these abstract
  114. methods may have an implementation. This implementation can be
  115. called via the :func:`super` mechanism from the class that
  116. overrides it. This could be useful as an end-point for a
  117. super-call in a framework that uses cooperative
  118. multiple-inheritance.
  119. .. function:: abstractproperty([fget[, fset[, fdel[, doc]]]])
  120. A subclass of the built-in :func:`property`, indicating an abstract property.
  121. Using this function requires that the class's metaclass is :class:`ABCMeta` or
  122. is derived from it.
  123. A class that has a metaclass derived from :class:`ABCMeta` cannot be
  124. instantiated unless all of its abstract methods and properties are overridden.
  125. The abstract properties can be called using any of the normal
  126. 'super' call mechanisms.
  127. Usage::
  128. class C:
  129. __metaclass__ = ABCMeta
  130. @abstractproperty
  131. def my_abstract_property(self):
  132. ...
  133. This defines a read-only property; you can also define a read-write abstract
  134. property using the 'long' form of property declaration::
  135. class C:
  136. __metaclass__ = ABCMeta
  137. def getx(self): ...
  138. def setx(self, value): ...
  139. x = abstractproperty(getx, setx)
  140. .. rubric:: Footnotes
  141. .. [#] C++ programmers should note that Python's virtual base class
  142. concept is not the same as C++'s.