Overloaded Constructors?!?

Shalabh Chaturvedi shalabh at cafepy.com
Sun Mar 20 18:49:32 EST 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:

<C++ code snipped>

> The 2 different initializations refers to completely different objects (the
> first one is a wx.Window, the second one is an horizontal line). 

> Does anyone know if is there a way to achieve the same thing in Python/wxPython?
> Someone else has talked about overloaded constructors, but I don't have
> any idea on how to implement this kind of "constructors" in Python. Does
> anyone have a small example of overloaded constructors in Python?
> I have no idea... Or am I missing something obvious?

If you do have to do something like this you could use keyword arguments 
with defaults. For example:

class C(object):
     def __init__(self, a=None, b=None):
         if None not in (a, b):
             raise some error (only one of a/b should be given)

         if a:
            # do something
         elif b:
            # do something else


Another way to do it is to use classmethods:

class C(object):

     def __init__(self):
         # do initialization

     def create_one(cls, a):
         obj = cls()
         # do something with a
         return obj

     create_one = classmethod(create_one)

     def create_two(cls, b):
         obj = cls()
         # do something with b
         return obj

     create_two = classmethod(create_two)

Then you can use it thus:

x = C.create_one(a='value')

y = C.create_two(b='value')

Because it is a classmethod, calling C.create_one('value') calls 
create_one() with two parameters:
- C
- 'value'

i.e. the first parameter is the class, not an instance of the class.

Hope this helped.

Shalabh







More information about the Python-list mailing list