Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #52530
| References | <520b913f$0$13995$426a74cc@news.free.fr> |
|---|---|
| From | Beth McNany <beth.mcnany@gmail.com> |
| Date | 2013-08-14 10:40 -0400 |
| Subject | Re: many constructors in a class? |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.585.1376503283.1251.python-list@python.org> (permalink) |
[Multipart message — attachments visible in raw view] - view raw
On Wed, Aug 14, 2013 at 10:16 AM, climb65 <climb65@laposte.net> 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
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
many constructors in a class? climb65 <climb65@laposte.net> - 2013-08-14 14:16 +0000
Re: many constructors in a class? Phil Le Bienheureux <phil.le.bienheureux@gmail.com> - 2013-08-14 16:46 +0200
Re: many constructors in a class? duncan smith <buzzard@invalid.invalid> - 2013-08-14 16:07 +0100
Re: many constructors in a class? Beth McNany <beth.mcnany@gmail.com> - 2013-08-14 10:40 -0400
Re: many constructors in a class? Dennis Lee Bieber <wlfraed@ix.netcom.com> - 2013-08-14 18:40 -0400
Re: many constructors in a class? Steven D'Aprano <steve@pearwood.info> - 2013-08-15 07:23 +0000
Re: many constructors in a class? Fábio Santos <fabiosantosart@gmail.com> - 2013-08-15 11:09 +0100
Re: many constructors in a class? Roy Smith <roy@panix.com> - 2013-08-15 09:00 -0400
csiph-web