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


Groups > comp.lang.python > #52517 > unrolled thread

many constructors in a class?

Started byclimb65 <climb65@laposte.net>
First post2013-08-14 14:16 +0000
Last post2013-08-15 09:00 -0400
Articles 8 — 8 participants

Back to article view | Back to comp.lang.python


Contents

  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

#52517 — many constructors in a class?

Fromclimb65 <climb65@laposte.net>
Date2013-08-14 14:16 +0000
Subjectmany constructors in a class?
Message-ID<520b913f$0$13995$426a74cc@news.free.fr>
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.

[toc] | [next] | [standalone]


#52520

FromPhil Le Bienheureux <phil.le.bienheureux@gmail.com>
Date2013-08-14 16:46 +0200
Message-ID<mailman.578.1376491597.1251.python-list@python.org>
In reply to#52517

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

2013/8/14 climb65 <climb65@laposte.net>

> 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.
> --
> http://mail.python.org/mailman/listinfo/python-list
>



Hello,

You have to use default values in __init__ function, like :
def __init__( self, name = None ):
        self.name_ = name

and afterwards in your code, test variable :
if self.name_:
       do something...

Regards,
Phil.

[toc] | [prev] | [next] | [standalone]


#52521

Fromduncan smith <buzzard@invalid.invalid>
Date2013-08-14 16:07 +0100
Message-ID<520b9d3d$0$7394$862e30e2@ngroups.net>
In reply to#52517
On 14/08/13 15:16, 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.
>


http://stackoverflow.com/questions/5738470/whats-an-example-use-case-for-a-python-classmethod


Duncan

[toc] | [prev] | [next] | [standalone]


#52530

FromBeth McNany <beth.mcnany@gmail.com>
Date2013-08-14 10:40 -0400
Message-ID<mailman.585.1376503283.1251.python-list@python.org>
In reply to#52517

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

On Wed, Aug 14, 2013 at 10:16 AM, climb65 <climb65@laposte.net> 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.
>
>
No, Python does not allow method overloading:

>>> class Test:
...  def __init__(self):
...    print "first init"
...  def __init__(self, arg):
...    print "init with arg"
...
>>> a = Test()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: __init__() takes exactly 2 arguments (1 given)

No error on actually writing the class, but only the last __init__ is
kept.  You could, however, emulate that behavior with optional arguments,
or something more sophisticated as the need may be.  This stackoverflow
question covers a few alternatives:
http://stackoverflow.com/questions/6434482/python-function-overloading

[toc] | [prev] | [next] | [standalone]


#52534

FromDennis Lee Bieber <wlfraed@ix.netcom.com>
Date2013-08-14 18:40 -0400
Message-ID<mailman.589.1376520059.1251.python-list@python.org>
In reply to#52517
On 14 Aug 2013 14:16:31 GMT, climb65 <climb65@laposte.net> declaimed the
following:

>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.
>
	Well... Secret Python-Fu -- __init__() is NOT a constructor. The
constructor is __new__(); __init__() is just an initializer of whatever
__new__() creates.


	Ignoring that detail... NO!

	If the goal is to be able to "leave out" some parameters, that is
performed by setting default values for the missing parameters.

	def __init__(self, these, are, mandatory, but=None, this=None, 
								is=None, optional=None):
		self.these = these
		self.are = are
		self.mandatory = mandatory
		if but is None:
			self.but = these + are
		else:
			self.but = but
	#etc.

-- 
	Wulfraed                 Dennis Lee Bieber         AF6VN
    wlfraed@ix.netcom.com    HTTP://wlfraed.home.netcom.com/

[toc] | [prev] | [next] | [standalone]


#52538

FromSteven D'Aprano <steve@pearwood.info>
Date2013-08-15 07:23 +0000
Message-ID<520c81f6$0$29885$c3e8da3$5496439d@news.astraweb.com>
In reply to#52517
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

[toc] | [prev] | [next] | [standalone]


#52546

FromFábio Santos <fabiosantosart@gmail.com>
Date2013-08-15 11:09 +0100
Message-ID<mailman.593.1376561401.1251.python-list@python.org>
In reply to#52538

[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
>

[toc] | [prev] | [next] | [standalone]


#52548

FromRoy Smith <roy@panix.com>
Date2013-08-15 09:00 -0400
Message-ID<roy-0FD4AE.09002715082013@news.panix.com>
In reply to#52538
In article <520c81f6$0$29885$c3e8da3$5496439d@news.astraweb.com>,
 Steven D'Aprano <steve@pearwood.info> wrote:

> [1] The constructor is __new__, not __init__. __init__ is called to 
> initialise the instance after __new__ constructs it.

True, but be warned that writing your own __new__() is quite rare and 
probably falls into the realm of dark magic.  If you're just starting 
out, learn about __init__(), and don't worry about __new__() at all.

For those of you coming from a C++ background, Python's __init__() is 
like C++'s constructor, and __new__() is more like operator new.  That's 
not a perfect analogy from a functional standpoint, but it's a good 
guide for how often you'll want to write each one.

And then, of course, there's __enter__() and __exit__(), which are like 
C++'s constructor and destructor, but that's another story :-)

[toc] | [prev] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web