程式扎記: [Python Std Library] Python Runtime Services : abc — Abstract Base Classes

標籤

2015年2月13日 星期五

[Python Std Library] Python Runtime Services : abc — Abstract Base Classes

Source From Here 
Preface 
This module provides the infrastructure for defining abstract base classes (ABCs) in Python, as outlined in PEP 3119; see the PEP for why this was added to Python. (See also PEP 3141 and the numbers module regarding a type hierarchy for numbers based on ABCs.

The collections module has some concrete classes that derive from ABCs; these can, of course, be further derived. In addition the collections module has some ABCs that can be used to test whether a class or instance provides a particular interface, for example, is it hashable or a mapping. 

This module provides the following class: 
class abc.ABCMeta 
Metaclass for defining Abstract Base Classes (ABCs).

Use this metaclass to create an ABC. An ABC can be subclassed directly, and then acts as a mix-in class. You can also register unrelated concrete classes (even built-in classes) and unrelated ABCs as “virtual subclasses” – these and their descendants will be considered subclasses of the registering ABC by the built-in issubclass() function, but the registering ABC won’t show up in their MRO (Method Resolution Order) nor will method implementations defined by the registering ABC be callable (not even via super()).

Classes created with a metaclass of ABCMeta have the following method: 
- register(subclass) 
Register subclass as a “virtual subclass” of this ABC. For example:
  1. from abc import ABCMeta  
  2.   
  3. class MyABC:  
  4.     __metaclass__ = ABCMeta  
  5.   
  6. MyABC.register(tuple)  
  7.   
  8. assert issubclass(tuple, MyABC)  
  9. assert isinstance((), MyABC)  
You can also override this method in an abstract base class:

- __subclasshook__(subclass) 
(Must be defined as a class method.)

Check whether subclass is considered a subclass of this ABC. This means that you can customize the behavior of issubclass further without the need to callregister() on every class you want to consider a subclass of the ABC. (This class method is called from the __subclasscheck__() method of the ABC.)

This method should return TrueFalse or NotImplemented. If it returns True, the subclass is considered a subclass of this ABC. If it returns False, the subclass is not considered a subclass of this ABC, even if it would normally be one. If it returns NotImplemented, the subclass check is continued with the usual mechanism.

For a demonstration of these concepts, look at this example ABC definition: 
  1. from abc import *  
  2.   
  3. class Foo(object):  
  4.     def __init__(self, *values):  
  5.         self.values = []  
  6.         for val in values:  
  7.             self.values.append(val)  
  8.       
  9.     def __getitem__(self, index):  
  10.         return self.values[index]  
  11.       
  12.     def __len__(self):  
  13.         return len(self.values)  
  14.       
  15.     def get_iterator(self):  
  16.         return iter(self)  
  17.       
  18. class Foo2(object):  
  19.     def __init__(self, *values):  
  20.         self.values = []  
  21.         for val in values:  
  22.             self.values.append(val)  
  23.               
  24.     def __iter__(self):  
  25.         return iter(self.values)  
  26.   
  27. class MyIterable:  
  28.     __metaclass__ = ABCMeta  
  29.   
  30.     @abstractmethod  
  31.     def __iter__(self):  
  32.         while False:  
  33.             yield None  
  34.   
  35.     def get_iterator(self):  
  36.         return self.__iter__()  
  37.   
  38.     @classmethod  
  39.     def __subclasshook__(cls, C):  
  40.         if cls is MyIterable:  
  41.             if any("__iter__" in B.__dict__ for B in C.__mro__):  
  42.                 return True  
  43.         return NotImplemented  
  44.   
  45. MyIterable.register(Foo)  
  46. #assert issubclass(Foo, MyIterable)    
  47. #assert isinstance(Foo().get_iterator(), MyIterable)    
  48.   
  49. foo = Foo(1,2,3,4,5,'a','b','c')  
  50. foo2 = Foo2(1,2,3,4,5,'a','b','c')  
  51. for iter_obj in [foo, foo2]:  
  52.     print("\t[Info] Iterate %s object:" % iter_obj.__class__.__name__)  
  53.     for v in iter_obj:  
  54.         print("\t%s" % v)  
  55.   
  56.       
  57. assert issubclass(Foo, MyIterable)   
  58. assert issubclass(Foo2, MyIterable)   
The ABC MyIterable defines the standard iterable method, __iter__(), as an abstract method. The implementation given here can still be called from subclasses. The get_iterator() method is also part of the MyIterable abstract base class, but it does not have to be overridden in non-abstract derived classes. 

The __subclasshook__() class method defined here says that any class that has an __iter__() method in its __dict__ (or in that of one of its base classes, accessed via the __mro__ list) is considered a MyIterable too. 

Finally, the line MyIterable.register(Foo) makes Foo a virtual subclass of MyIterable, even though it does not define an __iter__() method (it uses the old-style iterable protocol, defined in terms of __len__() and __getitem__()). Note that this will not make get_iterator available as a method of Foo, so it is provided separately. Also even through Foo2 doesn't get registered in MyIterable, because it has an __iter__() method, it will pass issubclass(Foo2, MyIterable) check. 

From abc module, it also provides the following decorators: 
abc.abstractmethod(function) 
A decorator indicating abstract methods.

Using this decorator requires that the class’s metaclass is ABCMeta or is derived from it. A class that has a metaclass derived from ABCMeta cannot be instantiated unless all of its abstract methods and properties are overridden. The abstract methods can be called using any of the normal ‘super’ call mechanisms.

Dynamically adding abstract methods to a class, or attempting to modify the abstraction status of a method or class once it is created, are not supported.The abstractmethod() only affects subclasses derived using regular inheritance; “virtual subclasses” registered with the ABC’s register() method are not affected.

Usage:
  1. class C:  
  2.     __metaclass__ = ABCMeta  
  3.     @abstractmethod  
  4.     def my_abstract_method(self, ...):  
  5.         pass  
Note. Unlike Java abstract methods, these abstract methods may have an implementation. This implementation can be called via the super() mechanism from the class that overrides it. This could be useful as an end-point for a super-call in a framework that uses cooperative multiple-inheritance.

abc.abstractproperty([fget[, fset[, fdel[, doc]]]]) 
A subclass of the built-in property(), indicating an abstract property.

Using this function requires that the class’s metaclass is ABCMeta or is derived from it. A class that has a metaclass derived from ABCMeta cannot be instantiated unless all of its abstract methods and properties are overridden. The abstract properties can be called using any of the normal ‘super’ call mechanisms.

Usage:
  1. class C:  
  2.     __metaclass__ = ABCMeta  
  3.     @abstractproperty  
  4.     def my_abstract_property(self):  
  5.         pass  
This defines a read-only property; you can also define a read-write abstract property using the ‘long’ form of property declaration:
  1. class C:  
  2.     __metaclass__ = ABCMeta  
  3.     def getx(self): ...  
  4.     def setx(self, value): ...  
  5.     x = abstractproperty(getx, setx)  

Below are sample code: 
  1. # -*- coding: utf-8 -*-  
  2. from abc import *  
  3.   
  4. class C:      
  5.     __metaclass__ = ABCMeta      
  6.       
  7.     def __init__(self):  
  8.         print("Initialization of C...")  
  9.         #self.name='Test'  
  10.       
  11.     def getname(self):   
  12.         return self.name  
  13.       
  14.     def setname(self, value):   
  15.         self.name = value  
  16.           
  17.     name = abstractproperty(getname, setname)  
  18.       
  19. class D(C):  
  20.     # Comment out below property will cause Error:  
  21.     # TypeError: Can't instantiate abstract class D with abstract methods name     
  22.     name = 'Test'  
  23.     def __init__(self):  
  24.         C.__init__(self)  
  25.         self.age=35          
  26.         print("Initialization of D...")  
  27.          
  28. d = D()  
  29. print("Name=%s" % d.name)  
  30. print("Age=%s" % d.age)  
If you remove property declaration of 'name' in class D, you will raise Error: 
 

Supplement 
Python 3.1 快速導覽 - 函數 不定個數參數 
Build-in Types - Iterator Types 
The Definitive Guide on How to Use Static, Class or Abstract Methods in Python

沒有留言:

張貼留言

網誌存檔