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


Groups > comp.lang.python > #19818

Re: multiple constructor __init__

References <CACB6ZmB9ofRz+ZAjqbbnwm2GfL9Vwth+jrz2mAQoMBp6-x5o2A@mail.gmail.com>
Date 2012-02-02 17:24 -0800
Subject Re: multiple constructor __init__
From Chris Rebert <clp2@rebertia.com>
Newsgroups comp.lang.python
Message-ID <mailman.5386.1328232270.27778.python-list@python.org> (permalink)

Show all headers | View raw


On Thu, Feb 2, 2012 at 5:09 PM, Emmanuel Mayssat <emayssat@gmail.com> wrote:
> Hello all,
>
> I would like to instantiate my class as follow
>
> QObject(<param1>, <parent>)
> QObject(<parent>)
>
> an example would be
> http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qmenu.html
>
> How can I do this without have to specify parent=<parent> in the second
> version
> (I always need to supply the parent parameter, but I would like to supply it
> last)
>
> I have read this
> http://stackoverflow.com/questions/356718/how-to-handle-constructors-or-methods-with-a-different-set-or-type-of-argument
> but all the suggested methods do not work as I want
>
> Any idea?

I believe you can approximate that using a keyword-only argument
without a default value:

# Untested!
# Requires Python 3.x
class QObject(object):
    def __init__(self, param1=some_default, *, parent):
        # …

obj1 = QObject(parent=daddy)
obj2 = QObject(arg1, parent=daddy)

obj3 = QObject(daddy) # ERROR
obj4 = QObject(arg1, daddy) # ERROR
obj5 = QObject() # ERROR

Cheers,
Chris
--
Using names instead of some arbitrary ordering makes much more sense.
http://rebertia.com

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


Thread

Re: multiple constructor __init__ Chris Rebert <clp2@rebertia.com> - 2012-02-02 17:24 -0800

csiph-web