My book says that function overloading is not possible in python but it asks me questions like:
WAP to find out the volume of a cube,cuboid and cylinder using function overloading.
Do I have to involve decorators here?
How am I supposed to involve functional overloading in my program?
I saw a similar question where wraps from functools was used but failed to understand it.
If functional overloading is not involved then it is child's play…
P.S-I am in grade 12 and we haven't been taught much about decorators.
Best Answer
If you're using Python 3.4 or newer, you have access to
functools.singledispatch
(thanks to PEP 443), which lets you overload functions (preferably unary) much like you would in a language like Java.If you define your various polyhedra as classes, you can dispatch on their types, like so:
Now, you can do this:
If you're using a version older than 3.4, you don't really have any good options for this sort of transparent single dispatch (though you could always just backport
functools.singledispatch
if you're on an earlier 3.x - it's written in pure Python and I don't think it relies on any new 3.4 features). You could, instead, have a functionvolume(cube=None, cuboid=None, cylinder=None)
, orvolume(polyhedron)
and dispatch ontype(polyhedron)
inside the function, or do some magic with**kwargs
.All that said, I somehow doubt that your book wants you to use
functools.singledispatch
- I'd hazard a guess that somebody just copied the problems out of a C++ or Java book without really thinking about it.