[Python-ideas] Adding multiple constructors on one class

Chris Angelico rosuav at gmail.com
Sun May 5 16:25:05 EDT 2019


On Mon, May 6, 2019 at 6:09 AM Zakariae Saih <zakasaih at gmail.com> wrote:
>
> Hello python team!
> you should consider adding the ability to create multiple constructors on one class like c# and Java it is really useful.
>  Example:
> i want a constructor takes 1 argument and other constructor takes 2 and another one takes none in the same class. so when i want to create an object i got a lot of options.
> i know i can do it by given a default value to the attribute but it will be better with multiple constructors
>

More generally: You want to be able to have multiple functions with
the same name, and have something distinguish them by their
signatures.

That's a difficult thing to do in Python, because there are so many
complexities (keyword arguments, a habit of duck typing, etc), but not
impossible. What you're looking for is sometimes called "multiple
dispatch", and you can find some packages on PyPI that offer this
feature - usually with some restrictions, eg distinguishing functions
by positional args only, or requiring an actual isinstance check
rather than "thing that can be added to an integer". Have a look at
some of them and see if they do what you want.

ChrisA


More information about the Python-ideas mailing list