[Tutor] The Template Pattern

Karim karim.liateni at free.fr
Sun Dec 19 20:27:28 CET 2010


Thanks a lot to point this out!

Karim

On 12/19/2010 04:33 AM, Steven D'Aprano wrote:
> Karim wrote:
>
>>> class InputStrategy( object ):
>>>     """This InputStrategy class is an abstract interface to various
>>>     read strategy objects.
>>>     """
>>>     def read(self, filePath):
>>>         """Abstract method to load into database memory an input file.
>>>         @arg: filePath - string - The input file path.
>>>         @return: The created database object.
>>>         """
>>>         raise NotImplementedError
>>>
>>> By the way, I use NotImplementedError in my abstract method of the 
>>> abstract class. You are using TypeError exception.
>>> Is there a general rule for that? NotImplementedError is ok?
>
>
> For abstract methods that should be overridden by a subclass, I would 
> use NotImplementedError, as you do. That is a clear convention for 
> saying "this method must be overridden".
>
> But __init__ is a special case. The __init__ method isn't merely not 
> implemented. It *is* implemented, and it does two jobs: it performs 
> any common initialization for the class and all subclasses, and it 
> also prevents the AbstractCLass from being instantiated.
>
> class AbstractClass:
>     def __init__(self, *args):
>         if type(self) is AbstractClass:
>             raise TypeError
>         # do common initialization here
>
> Trying to instantiate an AbstractClass is always an error:
>
> instance = AbstractClass(args)
>
> and the error is a *type* error -- you are trying to instantiate a 
> type that can't be. Python already does that, with the singletons 
> None, NotImplemented (different from NotImplementedError!), and Ellipsis:
>
> >>> type(None)()
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> TypeError: cannot create 'NoneType' instances
>
>
> TypeError means you have an error in your code. NotImplementedError 
> means the code is incomplete.
>
>
>
>>> I knew from Java experience that template method pattern is only a 
>>> kind of particular case of Stategy where you delegate
>>> parts of algorithm by abstract methods overriding. Indeed the base 
>>> class implements some common features and let
>>> derived classes implement particular parts by polymorphism.
>>> Now with your example, I don't understand why he had problems to 
>>> implement from C++ ?
>>> Or perhaps is he mixing it with C++ feature template <class T> ?!
>
> You'd have to ask him. Maybe he's just not a very good programmer, or 
> was having a bad day.
>
>
>
>



More information about the Tutor mailing list