0

I'm aware that multiple constructors in python is not possible.

However, I found the range class has two __init__ signatures from the official docs.

class range(stop)
class range(start, stop[, step])

At first I thought it's implemented like this def __init__(stop, start=None, step=None) But this will change the order of parameters for start and stop

So I check the python source code and the range class has the completely different methods here:

    def __init__(self, stop): # real signature unknown; restored from __doc__
        pass

    @staticmethod # known case of __new__
    def __new__(*args, **kwargs): # real signature unknown
        """ Create and return a new object.  See help(type) for accurate signature. """
        pass

Can anyone explain how it works? Can we do the same in our object class?

Is it something to do with single-dispatch?

Jeffery Li
  • 565
  • 1
  • 4
  • 13
  • 2
    Possible duplicate of https://stackoverflow.com/questions/43999181/range-non-default-parameter-follows-default-one (ran out of close votes, so this is just a comment). – MSeifert Aug 20 '19 at 17:36
  • 2
    Don't confuse overloading a single constructor *name* with having multiple constructors. A class method is essentially an alternate constructor. (`__init__` is *not* a constructor; it's an initializer. It receives as its first argument an already-constructed object.) – chepner Aug 20 '19 at 17:36
  • @MSeifert I think that’s the answer! Thank you very much ! – Jeffery Li Aug 20 '19 at 17:40
  • @chepner got you. Thank you – Jeffery Li Aug 20 '19 at 17:41

0 Answers0