can i implement virtual functions in python ?
Andrew Dalke
adalke at mindspring.com
Wed Oct 1 00:10:55 EDT 2003
logistix at cathoderaymission.net:
> if you want to create a genuine Abstract Base Class, raise
> NotImplementedErrors for the virual methods. People will tell you
> that this is not 'pythonic' (you should be using hasattr() to test for
> interfaces) but I still find it useful from time to time.
Really? I find hasattr to be non-Pythonic. Just get the object, like
try:
method = obj.function_name
except AttributeError:
... not implemented ...
However, I do use NotImplementedError so the exception
which percolates up is more obvious than AttributeError. It also
allows me to put in a docstring describing the interface requirements
of derived classes.
I also don't like the double attribute lookup in
if not hasattr(obj, "function_name"):
... not implemented ...
else:
obj.function_name(...)
but that's more a personal issue than Pythonic vs. non-Pythonic.
Andrew
dalke at dalkescientific.com
More information about the Python-list
mailing list