Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Re: multiple constructor __init__

10 views
Skip to first unread message

Chris Rebert

unread,
Feb 2, 2012, 8:24:23 PM2/2/12
to Emmanuel Mayssat, pytho...@python.org
On Thu, Feb 2, 2012 at 5:09 PM, Emmanuel Mayssat <emay...@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

Terry Reedy

unread,
Feb 2, 2012, 10:43:16 PM2/2/12
to pytho...@python.org
On 2/2/2012 8:09 PM, Emmanuel Mayssat 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)

The same way range(stop) versus range(start,stop) works.
But I really recommend against that api.
It makes both doc and code messy.
You need a really good reason to not use the obvious
def __init__(self, parent, param=default):...

--
Terry Jan Reedy

0 new messages