Overloaded Constructors?!?

Kent Johnson kent37 at tds.net
Sun Mar 20 23:13:27 CET 2005


andrea_gavana at tin.it wrote:
>  Hello NG,
> 
>    I am trying to port a useful class from wxWidgets (C++) to a pure Python/wxPython
> implementation. In the C++ source code, a unique class is initialized with
> 2 different methods (???). This is what it seems to me. I have this declarations:
> 
> class wxFoldWindowItem
> {
>     // wxWindow constructor. This initialises the class as a wxWindow type
>     wxFoldWindowItem(wxWindow *wnd, int flags = wxFPB_ALIGN_WIDTH, int ySpacing
> = wxFPB_DEFAULT_YSPACING,
>                      int leftSpacing = wxFPB_DEFAULT_LEFTSPACING, int rightSpacing
> = wxFPB_DEFAULT_RIGHTSPACING)
>         : _wnd(wnd)
>         , _type(WINDOW)
>         , _flags(flags)
>         , _leftSpacing(leftSpacing)
>         , _rightSpacing(rightSpacing)
>         , _ySpacing(ySpacing)
>         , _lineWidth(0)
>         , _lineY(0)
>     {
>     };
> 
>     // separator constructor. This initialises the class as a separator
> type
>     wxFoldWindowItem(int y, const wxColour &lineColor = *wxBLACK, int ySpacing
> = wxFPB_DEFAULT_YSPACING,
>                      int leftSpacing = wxFPB_DEFAULT_LEFTLINESPACING,
>                      int rightSpacing = wxFPB_DEFAULT_RIGHTLINESPACING)
> 
>         : _wnd(0)
>         , _type(SEPARATOR)
>         , _flags(wxFPB_ALIGN_WIDTH)
>         , _leftSpacing(leftSpacing)
>         , _rightSpacing(rightSpacing)
>         , _ySpacing(ySpacing)
>         , _lineWidth(0)
>         , _lineY(y)
>         , _sepLineColour(lineColor)
>     {
>     };
> 
> The 2 different initializations refers to completely different objects (the
> first one is a wx.Window, the second one is an horizontal line). 

This is a strange design. My first reaction is, why do you want to do that? Maybe you should split 
the class in two?

Next, there
> are a lot of functions that, depending on the variable _type, return properties
> of the wx.Window or of the line. I would like to keep the same names for
> classes/methods, so it would be useful to have the same class with 2 different
> "initializations".

One way to do this in Python is to have a single constructor that looks at the type / number of 
arguments to figure out what it is supposed to do. Another way is to make two factory methods that 
create instances of the class and do the correct initialization.

Kent



More information about the Python-list mailing list