Overloading Methods

K-Dawg kdawg44 at gmail.com
Tue Jan 20 21:19:45 CET 2009


Thank you for the explanation.  With my background in Java, I have to get
myself to think a little differently.
Kevin


On Tue, Jan 20, 2009 at 1:41 PM, Chris Rebert <clp2 at rebertia.com> wrote:

> On Tue, Jan 20, 2009 at 10:18 AM, MRAB <google at mrabarnett.plus.com> wrote:
> > K-Dawg wrote:
> >>
> >> Can you overload methods in Python?
> >>
> >> Can I have multiple __inits__ with different parameters passed in?
> >>
> > Simple answer: no.
>
> More complicated answer: Yes, with some caveats.
>
> You usually don't need to overload methods in Python since you can use
> default and keyword arguments instead. For instance:
>
> class Foo(object):
>    def __init__(self, a, b=10, c=None):
>        self.a = a
>        self.b = b
>        if c is None: c = []
>        self.c = c
>
> #example use
> x = Foo("#", 4, [6,7])
> y = Foo("@")
> z = Foo("!", c=[1,2])
>
> Whereas in Java or C++ this would require several overloads, it can be
> succinctly expressed as a single method in Python.
>
> However, if you want the overloads to accept completely different
> types as parameters, then it arguably should expressed as distinct
> methods rather than "overloads". In the special case of __init__, you
> might want to make the alternate initializers classmethods or factory
> functions.
>
> Cheers,
> Chris
>
> --
> Follow the path of the Iguana...
> http://rebertia.com
>  --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20090120/60af1fd3/attachment-0001.html>


More information about the Python-list mailing list