Overloading Methods

Chris Rebert clp2 at rebertia.com
Tue Jan 20 15:34:49 EST 2009


(top-posting just for consistency)

In that case, you might also be interested in:
http://dirtsimple.org/2004/12/python-is-not-java.html

Cheers,
Chris

On Tue, Jan 20, 2009 at 12:19 PM, K-Dawg <kdawg44 at gmail.com> wrote:
> 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
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>



-- 
Follow the path of the Iguana...
http://rebertia.com



More information about the Python-list mailing list