Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #52546

Re: many constructors in a class?

References <520b913f$0$13995$426a74cc@news.free.fr> <520c81f6$0$29885$c3e8da3$5496439d@news.astraweb.com>
Date 2013-08-15 11:09 +0100
Subject Re: many constructors in a class?
From Fábio Santos <fabiosantosart@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.593.1376561401.1251.python-list@python.org> (permalink)

Show all headers | View raw


[Multipart message — attachments visible in raw view] - view raw

I agree with Steven here.

classmethod is the best practise, most practical, readable, future-proof,
one obvious way to do it.
On 15 Aug 2013 08:29, "Steven D'Aprano" <steve@pearwood.info> wrote:

> On Wed, 14 Aug 2013 14:16:31 +0000, climb65 wrote:
>
> > Hello,
> >
> > here is a small basic question :
> >
> > Is it possible to have more than one constructor (__init__ function) in
> > a class? For instance, to create an object with 2 different ways? If my
> > memory is good, I think that with C++ it is possible.
> >
> > Thanks for your answer.
>
> Yes it is. The built-in type dict is a good example, there is the regular
> default constructor[1] that you can call like this:
>
> dict([('a', 100), ('b', 200)], spam=1, ham=2, eggs=3)
>
>
> Plus there is an alternative constructor that you can call like this:
>
> dict.fromkeys(['a', 'b', 'spam', 'ham', 'eggs'])
>
>
> The way to create an alternative constructor is to use a class method:
>
>
> def MyDict(dict):
>     @classmethod
>     def fromkeys(cls, keys):
>         ...
>
>
> If you need further details, please ask.
>
>
>
>
> [1] The constructor is __new__, not __init__. __init__ is called to
> initialise the instance after __new__ constructs it.
>
>
> --
> Steven
> --
> http://mail.python.org/mailman/listinfo/python-list
>

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

many constructors in a class? climb65 <climb65@laposte.net> - 2013-08-14 14:16 +0000
  Re: many constructors in a class? Phil Le Bienheureux <phil.le.bienheureux@gmail.com> - 2013-08-14 16:46 +0200
  Re: many constructors in a class? duncan smith <buzzard@invalid.invalid> - 2013-08-14 16:07 +0100
  Re: many constructors in a class? Beth McNany <beth.mcnany@gmail.com> - 2013-08-14 10:40 -0400
  Re: many constructors in a class? Dennis Lee Bieber <wlfraed@ix.netcom.com> - 2013-08-14 18:40 -0400
  Re: many constructors in a class? Steven D'Aprano <steve@pearwood.info> - 2013-08-15 07:23 +0000
    Re: many constructors in a class? Fábio Santos <fabiosantosart@gmail.com> - 2013-08-15 11:09 +0100
    Re: many constructors in a class? Roy Smith <roy@panix.com> - 2013-08-15 09:00 -0400

csiph-web