[Tutor] How many types of the constructor

Alan Gauld alan.gauld at btinternet.com
Tue Apr 28 01:16:39 CEST 2009


"sudhanshu gautam" <sudhanshu9252 at gmail.com> wrote

> Now If I placed the name of the constructor rather than the __init__
> __baba___ so will it also work as a constructor or constructor has 
> specified
> already if yes then give me list of them

Unlike some other OOP languages Python only has one constructor
(OK As Denis pointed out it has the pair of new and init). It does not
allow you to define multiple different constructors with different 
argument
lists.

We can fake this behaviour by defining the constructor to take an arbitrary
list of arguments and then based on the length of that list calling 
different
methods, something like (untested):

class C:
    def __init__(this, *args):
         if len(args) == 0:
             this._defaultConstructor()
         elif len(args) == 1:
             this._oneArg(args[0])
         elif len(args) == 2:
             this._twoArgs(args[0],args[1])
         else: raise ValueError

    def _default(this): print 'default'
    def _oneArg(this, a1): print "Arg - ", a1
    def _ twoArgs(this, a1,a2): print "Args - " a1, a2

c0 = C()                  # -> default
c1 = C('foo')           # -> Arg - foo
c2 = C('bar', 42)    # -> Args - bar 42
c3 = C(1,2,3)         # ->  error

The single _ is just a convention to indicate a "private"
method, that is one not intended for direct use

We can also use named arguments and default values
to achieve similar functionality. This is how the Widgets
in most GUIs work. You call the widget with a specifically
named subset of parameters. For example:

from Tkinter import *
top = Tk()
Label(top, text="OK", foreground="Blue).pack()
Label(top, text="Cancel").pack()
top.mainloop()

The second label just adopts the default colour scheme.

Hopefully this answers your question.

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/




More information about the Tutor mailing list