newbie-question: more then one constructor in a python-class?

Roy Smith roy at panix.com
Sun Jul 7 11:32:39 EDT 2002


"T. Kaufmann" <merman at snafu.de> wrote:
> is there a way to have more (then one) constructors in a python-class (like 
> in Java)?

Not really (and that's a good thing, IMHO).

You can achieve much the same effect, however, by doing something like:

class foo:
   def __init__ (self, string1=None, string2=None):

which allows you to create a foo instance with any of the following 
calls:

a = foo()
b = foo('spam')
c = foo('spam', 'eggs')

If you leave out a positional parameter, it defaults to None (at least 
it does in the example above).  You can build even more complicated 
constructors using the *args and **kwargs constructs.  See 
http://www.python.org/doc/current/ref/function.html for details.

That being said, I find that I only rarely use optional parameters, and 
I've never (in 5 years) found a need for using either the *args or 
**kwargs constructs.  That's not to say that they're not useful, or that 
you shouldn't use them, but the dynamic typing and inherent polymorphism 
of Python seems to make the "let's invent a zillion constructors for 
every possible combination of arguments" style so common in C++ (and, I 
guess from your posting, Java) less necessary.



More information about the Python-list mailing list