multiple constructor __init__

Chris Rebert clp2 at rebertia.com
Fri Feb 3 02:24:23 CET 2012


On Thu, Feb 2, 2012 at 5:09 PM, Emmanuel Mayssat <emayssat at 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



More information about the Python-list mailing list