FAQ

On Wed, Aug 14, 2013 at 10:16 AM, climb65 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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20130814/7c2194fd/attachment.html>

Search Discussions

Discussion Posts

Previous

Follow ups

Related Discussions

Discussion Navigation
viewthread | post
posts ‹ prev | 2 of 7 | next ›
Discussion Overview
grouppython-list @
categoriespython
postedAug 14, '13 at 2:16p
activeAug 15, '13 at 1:00p
posts7
users7
websitepython.org

People

Translate

site design / logo © 2021 Grokbase