Style for overwritten methods of abstract classes
Chris Liechti
cliechti at gmx.net
Thu Jan 3 16:21:44 EST 2002
Stefan Schwarzer <s.schwarzer at ndh.net> wrote in
news:3C34A6AE.4293E82C at ndh.net:
[snip example interface]
>
> I personally like this as an overview of which methods should be
> defined in derived classes. On the other hand, it may be considered
> verbose to write all of the above given that the methods would have
> to be overwritten anyway.
>
> Another aspect is that the "noop implementations" of __getitem__ and
> __setitem__ could actually obscure bugs if somebody forgets to overwrite
> the methods in derived classes.
>
> So I can think of three different approaches:
> 1. write the code as above [with pass/return None]
i would do this only for methods where a noop is save
> 2. merely describe the implementation/interfaces (e. g. in the class
> docstring or in a comment); write no code
you get an exception for some methods, but not for __init__ or __del__
raising an explicit NYI exception seems cleaner to me.
> 3. use code but let the abstract methods raise NotImplementedError
> instead of providing a default behaviour which might be useless
i prefer this one. this way you can't forget to implement something. this
comes close to javas or c++ "abstract".
things like __init__ or __del__ can use "pass" or just documentation,
because some implementation may work with empty methods for them.
(if __init__ must take some arguments i would go for "pass")
> (4. Are there others?)
>
> In the light of 2., __del__ might be a special case because it may be
> very important for clean-up and at the same time might go unnoticed
> for a while because Python will use its default behaviour regardless
> if __del__ had been defined in the abstract class or not.
most classes don't need a __del__ as python has a good memory management.
you _must have_ it only when you allocate external recources (e.g. files
are closed if all references to them are deleted, but if you open a serial
port as file it will be closed but the original settings are not
restored.).
>
> Which approach would you prefer and why? Can you think of criteria/cases
> where you would use one approach and in another case another approach?
>
> Thanks in advance for your replies.
>
> Stefan
>
--
Chris <cliechti at gmx.net>
More information about the Python-list
mailing list