FAQ
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.

Search Discussions

  • Beth McNany at Aug 14, 2013 at 2:40 pm

    On Wed, Aug 14, 2013 at 10:16 AM, 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.
    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
    -------------- next part --------------
    An HTML attachment was scrubbed...
    URL: <http://mail.python.org/pipermail/python-list/attachments/20130814/7c2194fd/attachment.html>
  • Phil Le Bienheureux at Aug 14, 2013 at 2:46 pm
    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.
    -------------- next part --------------
    An HTML attachment was scrubbed...
    URL: <http://mail.python.org/pipermail/python-list/attachments/20130814/74c8f152/attachment.html>
  • Duncan smith at Aug 14, 2013 at 3:07 pm

    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
  • Steven D'Aprano at Aug 15, 2013 at 7:23 am

    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
  • Fábio Santos at Aug 15, 2013 at 10:09 am
    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" 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
    -------------- next part --------------
    An HTML attachment was scrubbed...
    URL: <http://mail.python.org/pipermail/python-list/attachments/20130815/435b8b21/attachment.html>
  • Roy Smith at Aug 15, 2013 at 1:00 pm
    In article <520c81f6$0$29885$c3e8da3$5496439d at news.astraweb.com>,
      Steven D'Aprano 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 :-)

Related Discussions

Discussion Navigation
viewthread | post
Discussion Overview
grouppython-list @
categoriespython
postedAug 14, '13 at 2:16p
activeAug 15, '13 at 1:00p
posts7
users7
websitepython.org

People

Translate

site design / logo © 2021 Grokbase