FAQ
I agree with Steven here.


classmethod is the best practise, most practical, readable, future-proof,
one obvious way to do it.
On 15 Aug 2013 08:29, "Steven D'Aprano" wrote:

On Wed, 14 Aug 2013 14:16:31 +0000, 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.
Yes it is. The built-in type dict is a good example, there is the regular
default constructor[1] that you can call like this:

dict([('a', 100), ('b', 200)], spam=1, ham=2, eggs=3)


Plus there is an alternative constructor that you can call like this:

dict.fromkeys(['a', 'b', 'spam', 'ham', 'eggs'])


The way to create an alternative constructor is to use a class method:


def MyDict(dict):
@classmethod
def fromkeys(cls, keys):
...


If you need further details, please ask.




[1] The constructor is __new__, not __init__. __init__ is called to
initialise the instance after __new__ constructs it.


--
Steven
--
http://mail.python.org/mailman/listinfo/python-list
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20130815/435b8b21/attachment.html>

Search Discussions

Discussion Posts

Previous

Follow ups

Related Discussions

Discussion Navigation
viewthread | post
posts ‹ prev | 6 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 © 2022 Grokbase