Overloading Methods

"%s@gmail com" % myname.lower " ", \
Wed Jan 21 23:29:22 EST 2009


Chris Rebert 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
> 

To elaborate on what Chris said, I usually find myself using class 
factory functions. Suppose you have a class that you want to initialize 
from a string, a file pointer, or a path. Here's how I'd implement it:

class MyClass:
     def __init__(self, bytes):
         <whatever init code>

     @classmethod
     def FromFilePointer(self, fp):
         bytes = fp.read()
         return MyCass.FromBytes(bytes)

     @classmethod
     def FromPath(self, path):
         bytes = open(path, "r").read()
         return MyCass.FromBytes(bytes)

     @classmethod                #Yes, I know this duplicates __init__,
     def FromBytes(self, bytes): #but I include it so as to provide
         return MyClass(bytes)   #3 parallel methods for initializing.

myclass = MyClass.FromFilePointer(open("myfile.txt", "r"))
myclass = MyClass.FromPath("myfile.txt")
myclass = MyClass.FromBytes("spam-spam-spam")

That might be a little bit more work, but I think it reads better and is 
more flexible down the road.

-greg




More information about the Python-list mailing list