function overloading

Duncan Booth duncan at NOSPAMrcp.co.uk
Wed Jul 2 04:44:41 EDT 2003


"Simon Burton" <simonb at webone.com.au> wrote in 
news:pan.2003.07.01.19.42.06.202399 at webone.com.au:

> class Im:
>   def __init__(self,x,xx=None):
>     if xx is not None:
>       w,h = x,xx
>       im = Image.new("I",(w,h))
>     elif type(x)==str:
>       filename = x
>       im = Image.open(filename)
>     else:
>       im = x
>     self.im = im

I would probably do it like this:

class Im(object):
    def __init__(self,im):
        self.im = im

    def newFromFile(cls, fileName):
        im = Image.open(filename)
        return cls(im)
    newFromFile = classmethod(newFromFile)

    def newBlank(cls, width=640, height=480):
        im = Image.new("I",(width,height))
        return cls(im)
    newBlank = classmethod(newBlank)

Overloading is a bad idea, explicit is better than implicit.

Using class methods as alternate constructors lets you have meaningful 
parameter names, defaults for each variant (if you want them), and 
docstrings (here left as an exercise for the reader).


-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?




More information about the Python-list mailing list